telemetry library

Telemetry, tracing, metrics, and BigQuery agent analytics plugin.

Provides BaseTelemetryService, InMemoryTelemetryService, SqliteSpanExporter, and BigQueryAgentAnalyticsPlugin.

import 'package:adk_dart/telemetry.dart';

final telemetry = InMemoryTelemetryService();

Classes

AdkMetricRecord
One ADK metric sample.
AdkMetricsRecorder
Sink for ADK metric samples.
AdkOtelLogger
In-memory logger used by tracing helpers.
AdkTracer
In-memory tracer used by ADK telemetry utilities.
AgentEngineSpan
Span representation used by TopSpanProcessor to evaluate parent context and record the supportID attribute.
AgentEngineTelemetryContext
Immutable OpenTelemetry-style propagation context holding W3C baggage and an optional parent spanContext.
BaseTelemetryService
Contract for telemetry trace/span lifecycle services.
BatchLogRecordProcessor
Batch log record processor wrapper.
BatchProcessor
Batches BigQuery rows with RetryConfig exponential-backoff retries and a periodic batchFlushInterval timer.
BatchSpanProcessor
Batch span processor wrapper.
BigQueryAgentAnalyticsPlugin
Plugin that records ADK runtime events to BigQuery-compatible rows.
BigQueryDropStats
Snapshot of dropped or degraded analytics event counts.
BigQueryEventSink
Event sink abstraction used by BigQueryAgentAnalyticsPlugin.
BigQueryInsertAllEventSink
BigQueryEventSink implementation that writes rows using insertAll.
BigQueryLoggerConfig
Configuration for BigQueryAgentAnalyticsPlugin.
CloudLoggingExporter
Cloud Logging exporter descriptor.
CloudMonitoringMetricsExporter
Cloud Monitoring metrics exporter descriptor.
EventData
Per-event metadata captured in BigQuery rows.
EventLoggerProvider
Event logger provider wrapper around LoggerProvider.
GCPBatchLogRecordProcessor
Batching log record processor that keeps Cloud Logging log names and labels stable across local and Agent Engine environments.
GCSOffloader
Offloads oversized BigQuery analytics payloads to Cloud Storage.
GenAiCallable
Base representation of a callable layer over a GenAI SDK generateContent method.
GenAiClientInferenceData
Marker value attached to the active context while ADK's own inference span is open, mirroring opentelemetry.util.genai.invocation.InferenceData.
GenAiPlainWrapper
A plain function wrapper (analogous to < 1.0 functools.wraps replacement or an opaque plain foreign wrapper).
GenAiRawFunction
An unwrapped leaf SDK function (e.g. Models.generate_content).
GenAiWraptProxy
A wrapt-style proxy wrapper (used by opentelemetry-instrumentation-google-genai >= 1.0 and third-party wrapt wrappers).
GenerateContentSpan
Span wrapper for generate-content operations.
GoogleAuthResult
Google authentication payload for telemetry exporters.
HybridContentParser
Content parser and fail-closed credential sanitizer for BigQuery rows.
InMemoryAdkMetricsRecorder
Metrics recorder that stores samples in memory for tests and adapters.
InMemoryBigQueryEventSink
In-memory BigQueryEventSink for tests and local inspection.
InMemoryTelemetryService
In-memory telemetry implementation for local development and tests.
LoggerProvider
Logger provider container used by ADK telemetry setup.
LogRecordProcessor
Interface for log record processors used by a logger provider.
MeterProvider
Meter provider container used by ADK telemetry setup.
MetricReader
Interface for metric readers used by a meter provider.
ModalityTokenUsage
Per-modality token count entry.
NoopAdkMetricsRecorder
Metrics recorder that intentionally drops all samples.
OTelHooks
Collection of telemetry hooks to register on providers.
OTelLogRecord
In-memory OpenTelemetry log record.
OTelProviders
Registry of globally configured telemetry providers.
OTelResource
OpenTelemetry resource attributes used by telemetry providers.
OtlpLogExporter
OTLP/HTTP log exporter.
OtlpMetricExporter
OTLP/HTTP metric exporter.
OtlpSpanExporter
OTLP/HTTP span exporter.
PeriodicExportingMetricReader
Metric reader that periodically exports telemetry.
PropagatedTraceContext
Parsed W3C traceparent and tracestate context extracted from headers.
ReadableSpan
Readable span model used for export and retrieval.
RetryConfig
Retry policy used by BigQuery event delivery.
SkillTelemetry
Telemetry helper for naming and updating skill tool execution spans.
SpanContext
Span context identifier fields.
SpanEvent
Event recorded during a span's lifetime.
SpanExporter
Span exporter interface.
SpanProcessor
Interface for span processors used by a tracer provider.
SpanStatus
OpenTelemetry span status consisting of a statusCode and optional description.
SqliteSpanExporter
Web/WASM stub for SqliteSpanExporter, which requires local SQLite file I/O.
TelemetryConfig
Configuration for telemetry capture behavior.
TelemetryContext
Scoped telemetry context holder for node and agent execution.
TelemetryLogRecord
One log entry recorded under a telemetry span.
TelemetrySpan
Span model representing one traced operation.
TokenUsage
Aggregated token usage extracted from one or more LLM responses.
ToolResultClassification
Verdict returned by a ToolResultClassifier for a tool result.
TopSpanProcessor
Span processor that attaches Agent Engine's supportID attribute to the top-most span of a request.
TraceFlags
Trace flags for span context.
TracerProvider
Tracer provider container used by ADK telemetry setup.
TraceSpanRecord
In-memory representation of a trace span and its attributes.
TraceState
Trace-state key-value container.
WebUiLog
Structured log entry exported for the ADK Web UI trace viewer.
WebUiLogExporter
In-memory log exporter used by the ADK Web UI to correlate logs with spans.
WebUiSpan
Structured span snapshot exported for the ADK Web UI trace viewer.

Enums

ContentCapturingMode
Mirror of OpenTelemetry GenAI content-capturing modes.
SpanExportResult
Export result status.
SpanKind
OpenTelemetry span kind classification.
StatusCode
OpenTelemetry span status code classification.

Extensions

RunConfigTelemetryExtension on RunConfig
Attaches per-run TelemetryConfig to RunConfig.

Constants

adkCaptureMessageContentInSpans → const String
Environment key controlling whether request and response payloads are captured in span attributes.
adkExperimentalContextCacheContentsCount → const String
Attribute key recording context cache contents count.
adkExperimentalContextCacheFingerprint → const String
Attribute key recording context cache content fingerprint.
adkExperimentalContextCacheHit → const String
Attribute key indicating whether a cached content entry was hit.
adkExperimentalContextCacheInvocationsUsed → const String
Attribute key recording number of invocations that used the context cache.
adkExperimentalGroundingChunkCount → const String
Attribute key recording the count of grounding chunks returned by the model.
adkExperimentalGroundingQueryCount → const String
Attribute key recording the distinct count of grounding web search queries.
adkExperimentalGroundingSourceUris → const String
Attribute key recording the distinct grounding source URIs when content capture is enabled.
adkExperimentalGroundingWebSearchQueries → const String
Attribute key recording the grounding web search queries when content capture is enabled.
adkExperimentalInvokeAgentCacheReadInputTokensMetric → const String
Metric name for per-invocation cache-read input tokens.
adkExperimentalInvokeAgentInputTokensMetric → const String
Metric name for per-invocation input tokens.
adkExperimentalInvokeAgentOutputTokensMetric → const String
Metric name for per-invocation output tokens.
adkExperimentalInvokeAgentReasoningOutputTokensMetric → const String
Metric name for per-invocation reasoning output tokens.
adkExperimentalInvokeAgentSkillLoadsMetric → const String
Metric name for per-invocation skill loads.
adkExperimentalInvokeAgentToolInputTokensMetric → const String
Metric name for per-invocation tool input tokens.
adkExperimentalInvokeAgentTotalTokensMetric → const String
Metric name for per-invocation total tokens.
adkExperimentalInvokeWorkflowCacheReadInputTokensMetric → const String
Metric name for per-workflow cache-read input tokens.
adkExperimentalInvokeWorkflowCompactionsMetric → const String
Metric name for per-workflow compactions.
adkExperimentalInvokeWorkflowInferenceCallsMetric → const String
Metric name for per-workflow inference calls.
adkExperimentalInvokeWorkflowInputTokensMetric → const String
Metric name for per-workflow input tokens.
adkExperimentalInvokeWorkflowOutputTokensMetric → const String
Metric name for per-workflow output tokens.
adkExperimentalInvokeWorkflowReasoningOutputTokensMetric → const String
Metric name for per-workflow reasoning output tokens.
adkExperimentalInvokeWorkflowSkillLoadsMetric → const String
Metric name for per-workflow skill loads.
adkExperimentalInvokeWorkflowToolCallsMetric → const String
Metric name for per-workflow tool calls.
adkExperimentalInvokeWorkflowToolInputTokensMetric → const String
Metric name for per-workflow tool input tokens.
adkExperimentalInvokeWorkflowTotalTokensMetric → const String
Metric name for per-workflow total tokens.
adkExperimentalSkillLoadsMetric → const String
Metric name for skill loads.
adkExperimentalSkillScriptExecutionsMetric → const String
Metric name for skill script executions.
adkTelemetrySchemaVersionOptIn → const String
Environment variable pinning the ADK telemetry schema version (1 vs 2).
agentDurationBucketBounds → const List<double>
Explicit histogram bucket boundaries for agent invocation durations (s).
callCountBucketBounds → const List<int>
Explicit histogram bucket boundaries for agent call-count metrics.
credentialArgNames → const Set<String>
Normalized parameter and mapping-key names that commonly carry secrets.
credentialArgSuffixes → const List<String>
Normalized suffixes for compound secret parameter/key names.
credentialTypeNames → const Set<String>
Class names whose instances hold credential material across ADK, google.auth, and Pydantic secret types.
defaultAgentEngineLogName → const String
Default Cloud Logging log name used on Agent Engine runtimes.
defaultClientInferenceContextKey → const String
Default context key used by opentelemetry-util-genai >= 1.3b0 to detect an enclosing client inference span.
defaultGcpLogName → const String
Default Cloud Logging log name used by ADK telemetry.
defaultMtlsTelemetryLogsEndpoint → const String
Default mTLS Cloud Logging OTLP logs endpoint.
defaultMtlsTelemetryMetricsEndpoint → const String
Default mTLS Cloud Monitoring OTLP metrics endpoint.
defaultMtlsTelemetryTracesEndpoint → const String
Default mTLS Cloud Trace OTLP endpoint.
defaultTelemetryLogsEndpoint → const String
Default Cloud Logging OTLP logs endpoint.
defaultTelemetryMetricsEndpoint → const String
Default Cloud Monitoring OTLP metrics endpoint.
defaultTelemetryTracesEndpoint → const String
Default Cloud Trace OTLP endpoint.
experimentalInputTokenBucketBounds → const List<int>
Bucket boundaries for experimental input token histograms.
experimentalOutputTokenBucketBounds → const List<int>
Bucket boundaries for experimental output token histograms.
gcpLogNameEnvVariableName → const String
Environment key for overriding default Cloud Logging log name.
genAiAgentInvocationDurationMetric → const String
Metric name for agent invocation durations.
genAiAgentRequestSizeMetric → const String
Metric name for agent request sizes.
genAiAgentResponseSizeMetric → const String
Metric name for agent response sizes.
genAiClientInferenceChunkDurationMetric → const String
Metric name for inference chunk durations.
genAiClientInferenceDurationMetric → const String
Alias for genAiClientInferenceDurationMetricName.
genAiClientInferenceDurationMetricName → const String
Metric name for client inference durations.
genAiClientInferenceOperationInputTokensMetric → const String
Histogram metric name for semconv per-operation input token counts.
genAiClientInferenceOperationOutputTokensMetric → const String
Histogram metric name for semconv per-operation output token counts.
genAiClientInferenceTimePerOutputChunkMetric → const String
Metric name for time per output inference chunk.
genAiClientInferenceTimeToFirstChunkMetric → const String
Metric name for time to first inference chunk (semconv-aligned).
genAiClientInferenceUsageCacheReadInputTokensMetric → const String
Counter metric name for semconv cache-read input token usage.
genAiClientInferenceUsageCacheWriteInputTokensMetric → const String
Counter metric name for semconv cache-write input token usage.
genAiClientInferenceUsageInputTokensMetric → const String
Counter metric name for semconv input token usage.
genAiClientInferenceUsageOutputTokensMetric → const String
Counter metric name for semconv output token usage.
genAiClientInferenceUsageReasoningOutputTokensMetric → const String
Counter metric name for semconv reasoning output token usage.
genAiClientOperationDurationMetric → const String
Metric name for client operation durations.
genAiClientOperationTimeToFirstChunkMetric → const String
Metric name for time to first inference chunk.
genAiClientTokenUsageMetric → const String
Metric name for client token usage.
genAiExecuteToolDurationMetric → const String
Metric name for tool execution durations (semconv-aligned).
genAiInstrumentorModulePath → const String
Module path where opentelemetry-instrumentation-google-genai wrapper functions live across all releases.
genAiInvokeAgentDurationMetric → const String
Metric name for agent invocation durations (semconv-aligned).
genAiInvokeAgentInferenceCallsMetric → const String
Metric name for model calls made directly within an agent invocation.
genAiInvokeAgentToolCallsMetric → const String
Metric name for tool calls made directly within an agent invocation.
genAiInvokeWorkflowDurationMetric → const String
Metric name for workflow invocation durations (semconv-aligned).
genAiResponseModel → const String
Attribute key recording the model version that served the LLM response.
genAiToolExecutionDurationMetric → const String
Metric name for tool execution durations.
genAiToolRequestSizeMetric → const String
Metric name for tool request sizes.
genAiToolResponseSizeMetric → const String
Metric name for tool response sizes.
genAiWorkflowInvocationDurationMetric → const String
Metric name for workflow invocation durations.
googleAeTraceparentHeader → const String
Header set by Agent Engine carrying the caller's original traceparent.
googleCloudAgentEngineEnableTelemetryEnvVar → const String
Environment variable enabling Agent Engine telemetry user-agent headers.
googleCloudAgentEngineIdEnvVar → const String
Environment variable set when running inside Vertex AI Agent Engine.
googleTraceparentBaggageKey → const String
Baggage key storing the inbound traceparent header for supportID.
googleTraceparentHeader → const String
Standard W3C traceparent header name.
googleTraceparentSupportAttributeKey → const String
Span attribute key recording Agent Engine's internal traceparent.
lastInstrumentorWithoutInferenceTokenMetrics → const String
Last opentelemetry-instrumentation-google-genai version that did not emit gen_ai.client.token.usage metrics on its own.
lastUtilGenAiWithoutInferenceTokenMetrics → const String
The newest opentelemetry-util-genai release verified not to record the gen_ai.client.inference.* token metrics.
operationDurationBucketBounds → const List<double>
Explicit histogram bucket boundaries for tool and client operation durations (s).
otelExporterOtlpEndpoint → const String
Environment key for the base OTLP endpoint.
otelExporterOtlpLogsEndpoint → const String
Environment key for the OTLP logs endpoint.
otelExporterOtlpMetricsEndpoint → const String
Environment key for the OTLP metrics endpoint.
otelExporterOtlpTracesEndpoint → const String
Environment key for the OTLP traces endpoint.
otelInstrumentationGenaiCaptureMessageContent → const String
Environment key controlling prompt and response content logs for OpenTelemetry GenAI instrumentation.
otelResourceAttributes → const String
Environment key for comma-separated OpenTelemetry resource attributes.
otelServiceName → const String
Environment key for service name resource attribute.
projectablePayloadColumns → const Set<String>
Payload columns eligible for physical projection.
redacted → const String
Placeholder substituted for redacted credential values.
schemaVersionLegacy → const int
Legacy telemetry schema version (1 / otel_semconv_1_36).
schemaVersionSemconvAligned → const int
Semconv-aligned telemetry schema version (2 / otel_semconv_1_44).
tokenUsageBucketBounds → const List<int>
Explicit histogram bucket boundaries for token usage counts.
traceparentBaggageKey → const String
Baggage key storing the active parent traceparent string.
userContentElided → const String
Placeholder used when user content logging is disabled.
workflowDurationBucketBounds → const List<int>
Explicit histogram bucket boundaries for workflow invocation durations (s).

Properties

adkMetricsRecorder → AdkMetricsRecorder
The process-wide metrics recorder used by ADK helpers.
no setter
currentClientInferenceContextKey → Object
Returns the active context key used to mark ADK's enclosing inference span.
no setter
evalTableIdUnquotableRe → RegExp
Characters that cannot appear in a backtick-quoted BigQuery table or view ID.
final
globalOtelProviders → OTelProviders
Mutable global telemetry provider registry.
final
isUtilGenAiClientInferenceContextEnabled → bool
Whether ADK's inference span marks the active context for opentelemetry-util-genai >= 1.3b0.
no setter
otelLogger → AdkOtelLogger
Global in-memory OpenTelemetry logger.
final
tracer → AdkTracer
Global in-memory tracer.
final

Functions

buildEvalSessionQuerySql(String fullTableId, {Iterable<String>? deniedColumns, String whereClause = '', String rawWhereClause = ''}) → String
Builds a query that reads the rows of the eval_session view.
buildEvalSessionViewSql(String fullTableId, {String viewPrefix = 'v', Iterable<String>? deniedColumns}) → String
Builds the {viewPrefix}_eval_session view DDL.
buildEvalTurnQuerySql(String fullTableId, {Iterable<String>? deniedColumns, String whereClause = '', String rawWhereClause = ''}) → String
Builds a query that reads the rows of the eval_turn view.
buildEvalTurnViewSql(String fullTableId, {String viewPrefix = 'v', Iterable<String>? deniedColumns}) → String
Builds the {viewPrefix}_eval_turn view DDL.
contentSizeBytes(Content? content) → int
Returns the UTF-8 and inline-data byte size of content.
createClientInferenceData() → Object
Creates a new client inference context marker value.
detectOtelResourceFromEnvironment({Map<String, String>? environment}) → OTelResource
Builds an OTelResource from environment variables.
formatSkillToolSpanName({required String toolName, String? confirmedSkillName, String? confirmedResourceOrScriptPath}) → String
Formats an execute_tool span name for skill tools using confirmed (non-hallucinated) skill and resource/script identifiers.
genaiInstrumentorRecordsInference(TelemetryConfig telemetryConfig, {Map<String, String>? environment}) → bool
Returns true when the external opentelemetry-instrumentation-google-genai instrumentor records a Gemini inference under telemetryConfig.
getAgentEngineMetricsSetup({Object? exporter, Map<String, String>? environment}) → MetricsState?
Returns the cached MetricsState on Agent Engine when GOOGLE_CLOUD_AGENT_ENGINE_ID is set, or null otherwise.
getCurrentClientInferenceContextValue([Object? contextKey]) → Object?
Returns the client inference context value attached to the current Zone, or null when no ADK inference span is active.
getCurrentGenerateContentEventOnlyExtraAttributes() → Map<String, Object?>?
The current zone-scoped event-only attributes for generate-content logs.
getCurrentGenerateContentExtraAttributes() → Map<String, Object?>?
The current zone-scoped extra attributes for generate-content spans.
getCurrentInferenceSpan() → GenerateContentSpan?
Returns the active ADK GenerateContentSpan in the current Zone, or null when outside an ADK-owned inference span.
getElapsedSeconds({int? spanStartTimeUnixNano, int? spanEndTimeUnixNano, required int fallbackStartMicros, int? fallbackEndMicros}) → double
Computes elapsed duration in seconds from recorded span times when present, falling back to [fallbackStartMicros, fallbackEndMicros ?? now].
getGcpExporters({bool enableCloudTracing = false, bool enableCloudMetrics = false, bool enableCloudLogging = false, GoogleAuthResult? googleAuth, Map<String, String>? environment}) → OTelHooks
Returns telemetry hooks for Google Cloud exporters.
getGcpLogsExporter(String projectId, {Object? credentials, Map<String, String>? environment}) → LogRecordProcessor
Returns a Cloud Logging OTLP exporter hook.
getGcpMetricsExporter(String projectId, {Object? credentials, Map<String, String>? environment}) → MetricReader
Returns a Cloud Monitoring OTLP metrics exporter hook.
getGcpResource({String? projectId, Map<String, String>? environment, OTelResource gcpResourceDetector()?}) → OTelResource
Builds an OpenTelemetry resource enriched with Google Cloud attributes.
getGcpSpanExporter(Object credentials, {Map<String, String>? environment, bool hasDefaultClientCertificate = false, bool? useClientCertificate}) → SpanProcessor
Returns a Cloud Trace span exporter hook.
getGenAiGenerateContentWrapperForTest() → GenAiCallable?
Returns the simulated wrapped Models.generate_content callable, if set.
getGenAiInstrumentorVersionForTest() → String?
Returns the simulated opentelemetry-instrumentation-google-genai version, if set.
getOtelExporters({Map<String, String>? environment}) → OTelHooks
Detects OTLP exporter hooks from environment variables.
getOtelLogsExporter({Map<String, String>? environment}) → LogRecordProcessor
Default OTLP log exporter hook.
getOtelMetricsExporter({Map<String, String>? environment}) → MetricReader
Default OTLP metric exporter hook.
getOtelSpanExporter({Map<String, String>? environment}) → SpanProcessor
Default OTLP span exporter hook.
getPropagatedContext(Map<String, String> headers, {AgentEngineTelemetryContext? baseContext, Map<String, String>? environment}) → AgentEngineTelemetryContext
Extracts propagated W3C baggage, traceparent, tracestate, and Google-Agent-Engine-Traceparent context from HTTP request headers.
getUtilGenAiVersionForTest() → String?
Returns the simulated opentelemetry-util-genai package version, if set.
isCredentialArgName(String name) → bool
Returns true if name names a secret-bearing parameter or header.
isCredentialType(Object? value) → bool
Returns true if value (or Type token) is a known credential carrier.
isGeminiModelName(String? model) → bool
Returns true when model refers to a Google Gemini model.
isGenAiInstrumented() → bool
Returns true when external opentelemetry-instrumentation-google-genai instrumentation is active.
isGenAiInstrumentedCallable(GenAiCallable? callable) → bool
Returns true when callable has an opentelemetry-instrumentation-google-genai layer anywhere in its wrapper chain.
isGenAiInstrumentorCode(String? codeFilename) → bool
Returns true when codeFilename belongs to opentelemetry-instrumentation-google-genai.
isGenAiInstrumentorLayer(GenAiCallable callable) → bool
Returns true when callable is a layer added by opentelemetry-instrumentation-google-genai.
isInsideAdkInferenceSpan([Object? contextKey]) → bool
Returns true when execution is currently inside an ADK inference span that marked the context for opentelemetry-util-genai >= 1.3b0.
maskCredentialValues(Object? value, Object? dumped) → Object?
Walks live value alongside its JSON-dumped form dumped and masks any values whose live runtime type is a known credential carrier.
maybeSetOtelProviders({List<OTelHooks>? otelHooksToSetup, OTelResource? otelResource, Map<String, String>? environment, OTelProviders? providers}) → void
Initializes telemetry providers when exporters are available.
maybeWithoutGenAiInstrumentation(GenAiCallable method) → GenAiCallable
Returns method minus the opentelemetry-instrumentation-google-genai layer if ADK is currently recording the inference span itself.
recordAgentInvocationDuration(String agentName, Duration duration, {Object? error, AdkMetricsRecorder? recorder}) → void
Records the duration of an agent invocation.
recordAgentRequestSize(String agentName, Content? userContent, {AdkMetricsRecorder? recorder}) → void
Records the byte size of the user content sent to an agent.
recordAgentResponseSize(String agentName, List<Event>? events, {AdkMetricsRecorder? recorder}) → void
Records the byte size of the last response content authored by an agent.
recordClientInferenceChunk(Duration duration, {required bool isFirstChunk, String? agentName, String operationName = 'generate_content', String? requestModel, String? responseModel, String? system, String? providerName, String? serverAddress, int? serverPort, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records the latency of an inference chunk: either time to first chunk or time per output chunk (mutually exclusive).
recordClientInferenceDuration({required double elapsedS, required LlmRequest llmRequest, required List<LlmResponse> responses, Object? error, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records gen_ai.client.inference.duration.
recordClientOperationDuration(String agentName, Duration duration, {String operationName = 'generate_content', String? requestModel, String? responseModel, String? system, String? serverAddress, int? serverPort, List<String>? finishReasons, Object? error, AdkMetricsRecorder? recorder}) → void
Records the duration of a client operation (e.g., generate_content).
recordClientTokenUsage({required String agentName, required LlmRequest llmRequest, required List<LlmResponse> responses, String? system, String? serverAddress, int? serverPort, Object? error, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records client token usage metrics from responses, keeping usage from earlier responses when the final response carries none.
recordInferenceChunk(GenerateContentSpan? span, LlmResponse response, {int? nowMicros, AdkMetricsRecorder? recorder}) → void
Records streaming chunk timing metrics for response within span.
recordInferenceOutputTokenUsage(GenerateContentSpan? span, TokenUsage tokenUsage) → void
Records fallback tokenUsage on span for streaming or failed calls.
recordInferenceTokenUsage({required TokenUsage? tokenUsage, String? agentName, String operationName = 'generate_content', String? requestModel, String? responseModel, String? system, String? providerName, String? serverAddress, int? serverPort, List<String>? finishReasons, Object? error, AdkMetricsRecorder? recorder}) → void
Records semconv-genai inference token usage samples from tokenUsage, including detail and modality breakdowns, and optional error attributes for failed inference calls.
recordInvokeAgentInferenceCalls(String agentName, int count, {AdkMetricsRecorder? recorder}) → void
Records the number of model calls made directly within an agent invocation.
recordInvokeAgentSkillLoads(String agentName, int count, {TelemetryConfig? telemetryConfig, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records the number of skill loads in an agent invocation (gated on skills).
recordInvokeAgentTokenUsage(String agentName, TokenUsage totals, {TelemetryConfig? telemetryConfig, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records the token spend accumulated over one agent invocation (gated on token_usage).
recordInvokeAgentToolCalls(String agentName, int count, {AdkMetricsRecorder? recorder}) → void
Records the number of tool calls made directly within an agent invocation.
recordInvokeWorkflowCompactions({required String rootAgentName, String? workflowName, required int count, bool nested = false, TelemetryConfig? telemetryConfig, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records the conversation compactions made across one workflow (gated on compaction and workflow).
recordInvokeWorkflowInferenceCalls({required String rootAgentName, String? workflowName, required int count, bool nested = false, TelemetryConfig? telemetryConfig, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records the inference calls made across one workflow (gated on workflow).
recordInvokeWorkflowSkillLoads({required String rootAgentName, String? workflowName, required int count, bool nested = false, TelemetryConfig? telemetryConfig, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records the skill loads made across one workflow (gated on skills and workflow).
recordInvokeWorkflowTokenUsage({required String rootAgentName, String? workflowName, required TokenUsage totals, bool nested = false, TelemetryConfig? telemetryConfig, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records the token spend of one workflow (gated on workflow and token_usage).
recordInvokeWorkflowToolCalls({required String rootAgentName, String? workflowName, required int count, bool nested = false, TelemetryConfig? telemetryConfig, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records the tool calls made across one workflow (gated on workflow).
recordSemconvInferenceTokenUsage({required LlmRequest llmRequest, required List<LlmResponse> responses, Object? error, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records the 7 semconv-genai inference token metrics (gen_ai.client.inference.*).
recordSkillLoad({required String agentName, required MaybeHallucinated<String> skillName, String? errorType, TelemetryConfig? telemetryConfig, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records one skill load (gated on skills).
recordSkillScriptExecution({required String agentName, required MaybeHallucinated<String> skillName, required MaybeHallucinated<String> scriptPath, int? scriptExitCode, TelemetryConfig? telemetryConfig, Map<String, String>? environment, AdkMetricsRecorder? recorder}) → void
Records a skill script execution (gated on skills).
recordToolExecutionDuration(String toolName, String agentName, Duration duration, {String? toolType, Object? error, String? errorType, AdkMetricsRecorder? recorder}) → void
Records the duration of a tool execution.
recordToolRequestSize(String toolName, String agentName, Map<String, Object?> functionArgs, {AdkMetricsRecorder? recorder}) → void
Records the byte size of string-valued tool arguments.
recordToolResponseSize(String toolName, String agentName, Event? responseEvent, {AdkMetricsRecorder? recorder}) → void
Records the byte size of a tool response event.
recordWorkflowInvocationDuration(String workflowName, Duration duration, {bool nested = false, Object? error, AdkMetricsRecorder? recorder}) → void
Records the duration of a workflow invocation.
resetAdkMetricsRecorderForTest() → void
Restores the process-wide metrics recorder to a no-op recorder.
resetAgentEngineMetricsSetupForTest() → void
Clears the cached Agent Engine MetricsState for tests.
resetGenAiInstrumentationDetectorForTest() → void
Restores the default GenAI instrumentation detector.
resetGoogleAuthResolverForTest() → void
Restores the default Google auth resolver.
resetOtelLoggerForTest() → void
Clears global OpenTelemetry logs.
resetOtelProvidersForTest() → void
Clears all global telemetry providers.
resetUtilGenAiClientInferenceContextHookForTest() → void
Restores the default opentelemetry-util-genai client inference context hook.
resolveErrorType(Object error) → String
Resolves the OpenTelemetry error.type attribute value for error.
resolveGenAiProviderName(String? model, {Map<String, String>? environment}) → String
Resolves the semconv gen_ai.provider.name value for model.
resolveGenAiSystemNameV1(String? model, {Map<String, String>? environment}) → String
Resolves the legacy schema v1 gen_ai.system / provider name for model.
resolveTelemetryLogsEndpoint({Map<String, String>? environment, bool hasDefaultClientCertificate = false, bool? useClientCertificate}) → String
Resolves the telemetry logs endpoint using Google API mTLS environment.
resolveTelemetryMetricsEndpoint({Map<String, String>? environment, bool hasDefaultClientCertificate = false, bool? useClientCertificate}) → String
Resolves the telemetry metrics endpoint using Google API mTLS environment.
resolveTelemetrySchemaVersion({Map<String, String>? environment}) → int
Resolves the active ADK telemetry schema version (1 or 2).
resolveTelemetryTracesEndpoint({Map<String, String>? environment, bool hasDefaultClientCertificate = false, bool? useClientCertificate}) → String
Resolves the telemetry trace endpoint using Google API mTLS environment.
safeJsonSerialize(Object? value) → String
Serializes value to JSON while masking live credential carriers, stripping dumped AuthCredential / AuthConfig secret fields, and returning '<not serializable>' on circular references or failures.
setAdkMetricsRecorder(AdkMetricsRecorder recorder) → void
Sets the process-wide ADK metrics recorder.
setGenAiGenerateContentWrapperForTest(GenAiCallable? wrapper) → void
Sets the simulated wrapped Models.generate_content callable for tests.
setGenAiInstrumentationDetectorForTest(GenAiInstrumentationDetector detector, {String? version, String? utilGenAiVersion}) → void
Sets the detector used to identify external GenAI instrumentation.
setGenAiInstrumentorVersionForTest(String? version) → void
Sets the simulated opentelemetry-instrumentation-google-genai version for tests.
setGoogleAuthResolverForTest(GoogleAuthResolver resolver) → void
Overrides the Google auth resolver.
setUtilGenAiClientInferenceContextHookForTest({Object? contextKey, Object createInferenceData()?, bool enabled = true}) → void
Configures the opentelemetry-util-genai client inference context hook for tests.
setUtilGenAiVersionForTest(String? version) → void
Sets the simulated opentelemetry-util-genai package version for tests.
shouldEmitInferenceTokenMetrics({String? system, bool? hasGenAiInstrumentor, String? instrumentorVersion, Map<String, String>? environment}) → bool
Whether ADK should emit gen_ai.client.token.usage metrics.
shouldEmitSemconvInferenceTokenMetrics(String? model, {required bool hasGenAiInstrumentor, String? utilGenAiVersion, String? instrumentorVersion, Map<String, String>? environment}) → bool
Whether ADK should emit the 7 semconv-genai gen_ai.client.inference.* token metrics for model.
telemetryConfigFromInvocationContext(InvocationContext? invocationContext) → TelemetryConfig
Resolves TelemetryConfig from invocationContext if present.
telemetryUserAgentHeaders({Map<String, String>? environment, String agentPlatformVersion = '0.1.0', String? otlpExporterVersion}) → Map<String, String>?
Returns the Vertex Agent Engine User-Agent header map when telemetry is enabled via GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY, or null.
toolRequestSizeBytes(Map<String, Object?> functionArgs) → int
Returns the request byte size for string-valued tool arguments.
traceAgentInvocation(TraceSpanRecord span, BaseAgent agent, InvocationContext ctx) → void
Records span attributes for agent invocation metadata.
traceCallLlm(InvocationContext invocationContext, String eventId, LlmRequest llmRequest, LlmResponse llmResponse, {TraceSpanRecord? span, Map<String, String>? environment}) → void
Records span attributes for an LLM request and response pair.
traceGenerateContentResult(TraceSpanRecord? span, LlmResponse llmResponse, {Map<String, String>? environment}) → void
Records inference result attributes on a legacy span.
traceInferenceResult(Object? span, LlmResponse llmResponse, {InvocationContext? invocationContext, Map<String, String>? environment}) → void
Records inference result attributes on span.
traceMergedToolCalls(String responseEventId, Event functionResponseEvent, {InvocationContext? invocationContext, TraceSpanRecord? span, Map<String, String>? environment}) → void
Records span attributes for merged tool call responses.
traceSendData(InvocationContext invocationContext, String eventId, List<Content> data, {TraceSpanRecord? span, Map<String, String>? environment}) → void
Records span attributes for send-data events.
traceSpan<T>(BaseTelemetryService telemetryService, String name, Future<T> run(TelemetrySpan span), {String? parentSpanId, Map<String, Object?>? attributes}) → Future<T>
Runs run inside a telemetry span managed by telemetryService.
traceToolCall(BaseTool tool, Map<String, Object?> args, Event? functionResponseEvent, {Object? error, String? errorType, InvocationContext? invocationContext, TraceSpanRecord? span, Map<String, String>? environment}) → void
Records span attributes for a single tool call.
useGenerateContentSpan<T>(LlmRequest llmRequest, InvocationContext invocationContext, Event modelResponseEvent, Future<T> run(TraceSpanRecord? span), {Map<String, String>? environment}) → Future<T>
Runs run inside an inference span and passes a legacy span view.
useInferenceSpan<T>(LlmRequest llmRequest, InvocationContext invocationContext, Event modelResponseEvent, Future<T> run(GenerateContentSpan? span), {Map<String, String>? environment}) → Future<T>
Runs run inside a generate-content span context.
validatePayloadColumnDenylist(Iterable<String>? denylist) → Set<String>
Validates denylist and returns the immutable denied column set.
withoutGenAiInstrumentor(GenAiCallable method) → GenAiCallable
Returns method with the opentelemetry-instrumentation-google-genai layer removed, or method unchanged if no removable instrumentor layer is found.

Typedefs

BigQueryAccessTokenProvider = Future<String?> Function()
Async token provider used for BigQuery HTTP authentication.
BigQueryAnalyticsViewExecutor = Future<void> Function(List<String> statements)
Executes generated analytics view SQL statements.
BigQueryContentFormatter = Object? Function(Object? content, String eventType)
Formats raw event content before it is serialized for BigQuery.
BigQueryGcsUploadProvider = Future<String> Function({required String contentType, required List<int> data, required String path})
Uploads analytics content to Cloud Storage and returns a gs:// URI.
ContentParser = HybridContentParser
Alias for HybridContentParser matching upstream ContentParser name.
GenAiBoundFunction = FutureOr<Object?> Function(Object? instance, List<Object?> positionalArgs, Map<Symbol, Object?> namedArgs)
Callback signature for an underlying SDK function or plain wrapper body.
GenAiInstrumentationDetector = bool Function()
Callback that reports whether external GenAI instrumentation is active.
GenAiProxyWrapper = FutureOr<Object?> Function(GenAiCallable wrapped, Object? instance, List<Object?> positionalArgs, Map<Symbol, Object?> namedArgs)
Callback signature for a wrapt-style proxy wrapper function.
GoogleAuthResolver = GoogleAuthResult Function()
Resolver callback that provides GoogleAuthResult.
OtlpHttpPost = Future<void> Function(Uri uri, Map<String, String> headers, List<int> body)
HTTP POST callback used by OTLP/HTTP exporters.
ToolResultClassifier = ToolResultClassification? Function({required Object? result, required BaseTool tool, required Map<String, dynamic> toolArgs, required ToolContext toolContext})
Synchronous classifier signature used by observability plugins to classify tool results that report failures without throwing.
TraceSpan = TraceSpanRecord
Alias for TraceSpanRecord.