Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/google/adk/telemetry/_experimental_semconv.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,7 @@ def set_operation_details_common_attributes(
log_only_attributes: Mapping[str, AnyValue] | None = None,
) -> None:
operation_details_common_attributes.update(attributes)
if log_only_attributes and telemetry_config.should_add_content_to_logs:
if log_only_attributes and telemetry_config.should_add_user_id_to_logs:
operation_details_common_attributes.update(log_only_attributes)


Expand Down
50 changes: 50 additions & 0 deletions src/google/adk/telemetry/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@
# Names the experimental telemetry features to enable.
_ADK_EXPERIMENTAL_TELEMETRY_FEATURES = 'ADK_EXPERIMENTAL_TELEMETRY_FEATURES'

# Controls where user.id is stored (NO_CONTENT|EVENT_ONLY|SPAN_ONLY|SPAN_AND_EVENT).
ADK_STORE_USER_ID = 'ADK_STORE_USER_ID'

# Token in OTEL_SEMCONV_STABILITY_OPT_IN that selects experimental GenAI semconv.
_GENAI_EXPERIMENTAL_OPT_IN = 'gen_ai_latest_experimental'

Expand Down Expand Up @@ -189,6 +192,25 @@ def _read_ignore_per_request() -> bool:
return lock in _TRUTHY_ENV_VALUES


def _read_store_user_id() -> ContentCapturingMode | None:
"""Reads ``ADK_STORE_USER_ID`` (defaults to ``None``, unset)."""
stripped = os.getenv(ADK_STORE_USER_ID, '').strip()
if not stripped:
return None
try:
return ContentCapturingMode(stripped.upper())
except ValueError:
cache_key = f'{ADK_STORE_USER_ID}:{stripped}'
if cache_key not in _warnings_cache:
_warnings_cache.append(cache_key)
logger.warning(
'Ignoring unrecognized %s value: %s',
ADK_STORE_USER_ID,
stripped,
)
return None


class TelemetryConfig(BaseModel):
"""Per-request OpenTelemetry configuration.

Expand Down Expand Up @@ -241,6 +263,7 @@ class TelemetryConfig(BaseModel):
_env_enabled_experimental_features: frozenset[str] = PrivateAttr()
_env_ignore_per_request: bool = PrivateAttr()
_env_schema_version: int = PrivateAttr()
_env_store_user_id: ContentCapturingMode | None = PrivateAttr()

def model_post_init(self, context: Any, /) -> None:
"""Resolves the env-backed answers now, rather than on first read."""
Expand All @@ -254,6 +277,7 @@ def model_post_init(self, context: Any, /) -> None:
)
self._env_ignore_per_request = _read_ignore_per_request()
self._env_schema_version = resolve_schema_version()
self._env_store_user_id = _read_store_user_id()

def __eq__(self, other: object) -> bool:
"""Compares the fields, ignoring the env fallbacks cached beside them."""
Expand Down Expand Up @@ -332,6 +356,32 @@ def should_add_content_to_logs(self) -> bool:
ContentCapturingMode.SPAN_AND_EVENT,
)

@property
def store_user_id_mode(self) -> ContentCapturingMode | None:
"""The configured ``ADK_STORE_USER_ID`` mode, or ``None`` if unset."""
return self._env_store_user_id

@property
def should_add_user_id_to_spans(self) -> bool:
"""Whether ``user.id`` goes on inference spans."""
if self._env_store_user_id is None:
return False
return _is_span_bearing(self._env_store_user_id)

@property
def should_add_user_id_to_logs(self) -> bool:
"""Whether ``user.id`` goes on emitted inference log records.

Uses ``ADK_STORE_USER_ID`` when set; otherwise falls back to
:attr:`should_add_content_to_logs`.
"""
if self._env_store_user_id is not None:
return self._env_store_user_id in (
ContentCapturingMode.EVENT_ONLY,
ContentCapturingMode.SPAN_AND_EVENT,
)
return self.should_add_content_to_logs

@property
def should_add_content_to_experimental_spans(self) -> bool:
"""Whether content goes on semconv spans (inference, and v2 tool spans).
Expand Down
132 changes: 100 additions & 32 deletions src/google/adk/telemetry/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@
from ._stable_semconv import user_message_body
from ._token_usage import TokenUsage
from .context import _TRUTHY_ENV_VALUES
from .context import ContentCapturingMode
from .context import TelemetryConfig

# Use the import symbols once the minimum OpenTelemetry SDK version is updated to 1.40.0
Expand Down Expand Up @@ -179,6 +180,8 @@
# Silence unused warnings, but keep the public interface the same.
_ = OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT

_warned_missing_event_only_key = False

# Needed to avoid circular imports
if TYPE_CHECKING:
from opentelemetry.util.types import AnyValue
Expand Down Expand Up @@ -1095,6 +1098,48 @@ def _telemetry_config_from_invocation_context(
return TelemetryConfig()


def _build_inference_attributes(
agent: BaseAgent | BaseNode,
invocation_context: InvocationContext,
model_response_event: Event,
telemetry_config: TelemetryConfig,
) -> tuple[
dict[str, AttributeValue],
dict[str, AttributeValue],
dict[str, AttributeValue],
dict[str, AttributeValue],
]:
"""Builds common, span, log-only, and delegated log-only inference attrs."""
common_attributes: dict[str, AttributeValue] = {
GEN_AI_AGENT_NAME: agent.name,
GEN_AI_CONVERSATION_ID: invocation_context.session.id,
"gcp.vertex.agent.event_id": model_response_event.id,
"gcp.vertex.agent.invocation_id": invocation_context.invocation_id,
}
user_id = invocation_context.session.user_id
span_attributes = dict(common_attributes)
log_only_common_attributes: dict[str, AttributeValue] = {}
if user_id is not None:
log_only_common_attributes[USER_ID] = user_id
if telemetry_config.should_add_user_id_to_spans:
span_attributes[USER_ID] = user_id

if (
telemetry_config.store_user_id_mode is ContentCapturingMode.NO_CONTENT
or telemetry_config.should_add_user_id_to_spans
):
delegated_log_only_attributes: dict[str, AttributeValue] = {}
else:
delegated_log_only_attributes = dict(log_only_common_attributes)

return (
common_attributes,
span_attributes,
log_only_common_attributes,
delegated_log_only_attributes,
)


@deprecated("Replaced by use_inference_span to support experimental semconv.")
@contextmanager
def use_generate_content_span(
Expand All @@ -1115,27 +1160,27 @@ def use_generate_content_span(
agent = invocation_context.agent
if agent is None:
raise ValueError("The invocation context must have an agent.")
common_attributes = {
GEN_AI_AGENT_NAME: agent.name,
GEN_AI_CONVERSATION_ID: invocation_context.session.id,
"gcp.vertex.agent.event_id": model_response_event.id,
"gcp.vertex.agent.invocation_id": invocation_context.invocation_id,
}
log_only_common_attributes = {}
if invocation_context.session.user_id is not None:
log_only_common_attributes[USER_ID] = invocation_context.session.user_id
(
_,
span_attributes,
log_only_common_attributes,
delegated_log_only_attributes,
) = _build_inference_attributes(
agent, invocation_context, model_response_event, telemetry_config
)
if _should_emit_native_telemetry(agent, telemetry_config):
with _use_native_generate_content_span_stable_semconv(
llm_request=llm_request,
common_attributes=common_attributes,
common_attributes=span_attributes,
log_only_common_attributes=log_only_common_attributes,
telemetry_config=telemetry_config,
) as span:
yield span.span
else:
with _use_extra_generate_content_attributes(
common_attributes,
log_only_extra_attributes=log_only_common_attributes,
span_attributes,
log_only_extra_attributes=delegated_log_only_attributes,
telemetry_config=telemetry_config,
):
yield None

Expand All @@ -1159,15 +1204,14 @@ async def use_inference_span(
agent = invocation_context.agent
if agent is None:
raise ValueError("The invocation context must have an agent.")
common_attributes = {
GEN_AI_AGENT_NAME: agent.name,
GEN_AI_CONVERSATION_ID: invocation_context.session.id,
"gcp.vertex.agent.event_id": model_response_event.id,
"gcp.vertex.agent.invocation_id": invocation_context.invocation_id,
}
log_only_common_attributes = {}
if invocation_context.session.user_id is not None:
log_only_common_attributes[USER_ID] = invocation_context.session.user_id
(
common_attributes,
span_attributes,
log_only_common_attributes,
delegated_log_only_attributes,
) = _build_inference_attributes(
agent, invocation_context, model_response_event, telemetry_config
)
if _should_emit_native_telemetry(agent, telemetry_config):
if (
telemetry_config.should_use_experimental_genai_semconv
Expand All @@ -1176,14 +1220,14 @@ async def use_inference_span(
# Semconv >= 1.37 replaces `gen_ai.system`; both are kept for consumers.
# Schema v1 keeps `gen_ai.system` only, as it did before the provider
# name existed.
common_attributes[GEN_AI_PROVIDER_NAME] = _resolve_gen_ai_provider_name(
llm_request.model
)
provider_name = _resolve_gen_ai_provider_name(llm_request.model)
common_attributes[GEN_AI_PROVIDER_NAME] = provider_name
span_attributes[GEN_AI_PROVIDER_NAME] = provider_name
with ExitStack() as stack:
gc_span = stack.enter_context(
_use_native_generate_content_span(
llm_request=llm_request,
common_attributes=common_attributes,
common_attributes=span_attributes,
log_only_common_attributes=log_only_common_attributes,
telemetry_config=telemetry_config,
)
Expand Down Expand Up @@ -1213,8 +1257,9 @@ def _log_completion_details() -> None:
yield gc_span
else:
with _use_extra_generate_content_attributes(
common_attributes,
log_only_extra_attributes=log_only_common_attributes,
span_attributes,
log_only_extra_attributes=delegated_log_only_attributes,
telemetry_config=telemetry_config,
):
yield None

Expand All @@ -1236,7 +1281,9 @@ def _should_emit_native_telemetry(
def _use_extra_generate_content_attributes(
extra_attributes: Mapping[str, AttributeValue],
log_only_extra_attributes: Mapping[str, AttributeValue] | None = None,
telemetry_config: TelemetryConfig | None = None,
) -> Iterator[None]:
global _warned_missing_event_only_key
try:
from opentelemetry.instrumentation.google_genai import GENERATE_CONTENT_EXTRA_ATTRIBUTES_CONTEXT_KEY
except (ImportError, AttributeError):
Expand All @@ -1250,10 +1297,22 @@ def _use_extra_generate_content_attributes(

return

effective_config = telemetry_config or TelemetryConfig()
resolved_extra_attributes: dict[str, AttributeValue] = dict(extra_attributes)
remaining_log_only = (
dict(log_only_extra_attributes) if log_only_extra_attributes else {}
)
if remaining_log_only:
if effective_config.should_add_user_id_to_spans:
resolved_extra_attributes.update(remaining_log_only)
remaining_log_only = {}
elif effective_config.store_user_id_mode is ContentCapturingMode.NO_CONTENT:
remaining_log_only = {}

ctx = otel_context.set_value(
GENERATE_CONTENT_EXTRA_ATTRIBUTES_CONTEXT_KEY, extra_attributes
GENERATE_CONTENT_EXTRA_ATTRIBUTES_CONTEXT_KEY, resolved_extra_attributes
)
if log_only_extra_attributes:
if remaining_log_only:
try:
from opentelemetry.instrumentation import google_genai

Expand All @@ -1264,11 +1323,20 @@ def _use_extra_generate_content_attributes(
)
ctx = otel_context.set_value(
event_only_key,
log_only_extra_attributes,
remaining_log_only,
context=ctx,
)
except (ImportError, AttributeError):
pass
if not _warned_missing_event_only_key:
_warned_missing_event_only_key = True
logger.warning(
"opentelemetry-instrumentation-google-genai does not export"
" GENERATE_CONTENT_EVENT_ONLY_EXTRA_ATTRIBUTES_CONTEXT_KEY; %s"
" will not be attached to instrumented telemetry. Set"
" ADK_STORE_USER_ID=SPAN_ONLY or SPAN_AND_EVENT to attach it"
" via GENERATE_CONTENT_EXTRA_ATTRIBUTES_CONTEXT_KEY.",
", ".join(sorted(remaining_log_only)),
)

tok = otel_context.attach(ctx)
try:
Expand Down Expand Up @@ -1325,7 +1393,7 @@ def _use_native_generate_content_span_stable_semconv(
GEN_AI_SYSTEM: system_name
}
if (
telemetry_config.should_add_content_to_logs
telemetry_config.should_add_user_id_to_logs
and log_only_common_attributes
):
user_id = log_only_common_attributes.get(USER_ID)
Expand Down
41 changes: 41 additions & 0 deletions tests/unittests/telemetry/test_genai_instrumentor_bypass.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,3 +427,44 @@ async def sdk_stub_with_usage(
for point in metric.data.data_points
]
assert (point.count, point.sum) == (1, 10)


@pytest.mark.parametrize(
"store_user_id_mode,expect_user_id_on_span",
[
(None, False),
("NO_CONTENT", False),
("EVENT_ONLY", False),
("SPAN_ONLY", True),
("SPAN_AND_EVENT", True),
],
)
@pytest.mark.asyncio
async def test_instrumented_span_records_user_id_when_opted_in(
monkeypatch: pytest.MonkeyPatch,
provider: TracerProvider,
store_user_id_mode: str | None,
expect_user_id_on_span: bool,
) -> None:
"""``ADK_STORE_USER_ID`` controls ``user.id`` on the instrumentor's span."""
monkeypatch.setenv("ADK_TELEMETRY_SCHEMA_VERSION_OPT_IN", "2")
monkeypatch.setenv("OTEL_SEMCONV_STABILITY_OPT_IN", _EXPERIMENTAL)
if store_user_id_mode is None:
monkeypatch.delenv("ADK_STORE_USER_ID", raising=False)
else:
monkeypatch.setenv("ADK_STORE_USER_ID", store_user_id_mode)

with _instrumented(monkeypatch, provider) as exporter:
await _run_inference(TelemetryConfig())

gen_ai_spans = [
span
for span in exporter.get_finished_spans()
if span.name.startswith("generate_content")
]
assert len(gen_ai_spans) == 1
attrs = gen_ai_spans[0].attributes or {}
if expect_user_id_on_span:
assert attrs.get("user.id") == "test_user"
else:
assert "user.id" not in attrs
Loading