@google/adk 0.1.2 → 0.2.0

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.
Files changed (57) hide show
  1. package/dist/cjs/agents/content_processor_utils.js +20 -8
  2. package/dist/cjs/agents/functions.js +23 -32
  3. package/dist/cjs/agents/llm_agent.js +1 -0
  4. package/dist/cjs/artifacts/gcs_artifact_service.js +140 -0
  5. package/dist/cjs/common.js +12 -0
  6. package/dist/cjs/index.js +5 -5
  7. package/dist/cjs/index.js.map +4 -4
  8. package/dist/cjs/models/base_llm.js +12 -3
  9. package/dist/cjs/models/google_llm.js +6 -20
  10. package/dist/cjs/models/registry.js +1 -1
  11. package/dist/cjs/telemetry/google_cloud.js +85 -0
  12. package/dist/cjs/telemetry/setup.js +97 -0
  13. package/dist/cjs/telemetry/tracing.js +231 -0
  14. package/dist/cjs/utils/client_labels.js +56 -0
  15. package/dist/cjs/version.js +1 -1
  16. package/dist/esm/agents/content_processor_utils.js +20 -8
  17. package/dist/esm/agents/functions.js +23 -32
  18. package/dist/esm/agents/llm_agent.js +1 -0
  19. package/dist/esm/artifacts/gcs_artifact_service.js +110 -0
  20. package/dist/esm/common.js +8 -0
  21. package/dist/esm/index.js +5 -5
  22. package/dist/esm/index.js.map +4 -4
  23. package/dist/esm/models/base_llm.js +12 -3
  24. package/dist/esm/models/google_llm.js +6 -20
  25. package/dist/esm/models/registry.js +1 -1
  26. package/dist/esm/telemetry/google_cloud.js +54 -0
  27. package/dist/esm/telemetry/setup.js +67 -0
  28. package/dist/esm/telemetry/tracing.js +195 -0
  29. package/dist/esm/utils/client_labels.js +26 -0
  30. package/dist/esm/version.js +1 -1
  31. package/dist/types/artifacts/gcs_artifact_service.d.ts +16 -0
  32. package/dist/types/common.d.ts +4 -0
  33. package/dist/types/index.d.ts +3 -0
  34. package/dist/types/models/base_llm.d.ts +6 -3
  35. package/dist/types/models/google_llm.d.ts +1 -2
  36. package/dist/types/models/registry.d.ts +6 -2
  37. package/dist/types/telemetry/google_cloud.d.ts +9 -0
  38. package/dist/types/telemetry/setup.d.ts +48 -0
  39. package/dist/types/telemetry/tracing.d.ts +111 -0
  40. package/dist/types/utils/client_labels.d.ts +9 -0
  41. package/dist/types/version.d.ts +1 -1
  42. package/dist/web/agents/content_processor_utils.js +20 -8
  43. package/dist/web/agents/functions.js +23 -32
  44. package/dist/web/agents/llm_agent.js +1 -0
  45. package/dist/web/artifacts/gcs_artifact_service.js +126 -0
  46. package/dist/web/common.js +8 -0
  47. package/dist/web/index.js +1 -1
  48. package/dist/web/index.js.map +4 -4
  49. package/dist/web/models/base_llm.js +12 -3
  50. package/dist/web/models/google_llm.js +6 -20
  51. package/dist/web/models/registry.js +1 -1
  52. package/dist/web/telemetry/google_cloud.js +54 -0
  53. package/dist/web/telemetry/setup.js +67 -0
  54. package/dist/web/telemetry/tracing.js +210 -0
  55. package/dist/web/utils/client_labels.js +26 -0
  56. package/dist/web/version.js +1 -1
  57. package/package.json +20 -4
@@ -27,6 +27,7 @@ __export(base_llm_exports, {
27
27
  BaseLlm: () => BaseLlm
28
28
  });
29
29
  module.exports = __toCommonJS(base_llm_exports);
30
+ var import_client_labels = require("../utils/client_labels.js");
30
31
  /**
31
32
  * @license
32
33
  * Copyright 2025 Google LLC
@@ -35,13 +36,21 @@ module.exports = __toCommonJS(base_llm_exports);
35
36
  class BaseLlm {
36
37
  /**
37
38
  * Creates an instance of BaseLLM.
38
- *
39
- * @param model The name of the LLM, e.g. gemini-1.5-flash or
39
+ * @param params The parameters for creating a BaseLlm instance.
40
+ * @param params.model The name of the LLM, e.g. gemini-1.5-flash or
40
41
  * gemini-1.5-flash-001.
41
42
  */
42
- constructor(model) {
43
+ constructor({ model }) {
43
44
  this.model = model;
44
45
  }
46
+ get trackingHeaders() {
47
+ const labels = (0, import_client_labels.getClientLabels)();
48
+ const headerValue = labels.join(" ");
49
+ return {
50
+ "x-goog-api-client": headerValue,
51
+ "user-agent": headerValue
52
+ };
53
+ }
45
54
  /**
46
55
  * Appends a user content, so that model can continue to output.
47
56
  *
@@ -28,10 +28,8 @@ __export(google_llm_exports, {
28
28
  });
29
29
  module.exports = __toCommonJS(google_llm_exports);
30
30
  var import_genai = require("@google/genai");
31
- var import_env_aware_utils = require("../utils/env_aware_utils.js");
32
31
  var import_logger = require("../utils/logger.js");
33
32
  var import_variant_utils = require("../utils/variant_utils.js");
34
- var import_version = require("../version.js");
35
33
  var import_base_llm = require("./base_llm.js");
36
34
  var import_gemini_llm_connection = require("./gemini_llm_connection.js");
37
35
  var import_llm_response = require("./llm_response.js");
@@ -47,14 +45,17 @@ class Gemini extends import_base_llm.BaseLlm {
47
45
  * @param params The parameters for creating a Gemini instance.
48
46
  */
49
47
  constructor({
50
- model = "gemini-2.5-flash",
48
+ model,
51
49
  apiKey,
52
50
  vertexai,
53
51
  project,
54
52
  location,
55
53
  headers
56
- } = {}) {
57
- super(model);
54
+ }) {
55
+ if (!model) {
56
+ model = "gemini-2.5-flash";
57
+ }
58
+ super({ model });
58
59
  this.project = project;
59
60
  this.location = location;
60
61
  this.apiKey = apiKey;
@@ -211,21 +212,6 @@ class Gemini extends import_base_llm.BaseLlm {
211
212
  }
212
213
  return this._apiBackend;
213
214
  }
214
- get trackingHeaders() {
215
- if (!this._trackingHeaders) {
216
- let frameworkLabel = `google-adk/${import_version.version}`;
217
- if (!(0, import_env_aware_utils.isBrowser)() && process.env[AGENT_ENGINE_TELEMETRY_ENV_VARIABLE_NAME]) {
218
- frameworkLabel = `${frameworkLabel}+${AGENT_ENGINE_TELEMETRY_TAG}`;
219
- }
220
- const languageLabel = `gl-typescript/${(0, import_env_aware_utils.isBrowser)() ? window.navigator.userAgent : process.version}`;
221
- const versionHeaderValue = `${frameworkLabel} ${languageLabel}`;
222
- this._trackingHeaders = {
223
- "x-goog-api-client": versionHeaderValue,
224
- "user-agent": versionHeaderValue
225
- };
226
- }
227
- return this._trackingHeaders;
228
- }
229
215
  get liveApiVersion() {
230
216
  if (!this._liveApiVersion) {
231
217
  this._liveApiVersion = this.apiBackend === import_variant_utils.GoogleLLMVariant.VERTEX_AI ? "v1beta1" : "v1alpha";
@@ -64,7 +64,7 @@ const _LLMRegistry = class _LLMRegistry {
64
64
  * @returns The LLM instance.
65
65
  */
66
66
  static newLlm(model) {
67
- return new (_LLMRegistry.resolve(model))(model);
67
+ return new (_LLMRegistry.resolve(model))({ model });
68
68
  }
69
69
  static _register(modelNameRegex, llmCls) {
70
70
  if (_LLMRegistry.llmRegistryDict.has(modelNameRegex)) {
@@ -0,0 +1,85 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+ var google_cloud_exports = {};
26
+ __export(google_cloud_exports, {
27
+ getGcpExporters: () => getGcpExporters,
28
+ getGcpResource: () => getGcpResource
29
+ });
30
+ module.exports = __toCommonJS(google_cloud_exports);
31
+ var import_google_auth_library = require("google-auth-library");
32
+ var import_sdk_metrics = require("@opentelemetry/sdk-metrics");
33
+ var import_resources = require("@opentelemetry/resources");
34
+ var import_resource_detector_gcp = require("@opentelemetry/resource-detector-gcp");
35
+ var import_opentelemetry_cloud_trace_exporter = require("@google-cloud/opentelemetry-cloud-trace-exporter");
36
+ var import_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
37
+ var import_opentelemetry_cloud_monitoring_exporter = require("@google-cloud/opentelemetry-cloud-monitoring-exporter");
38
+ var import_logger = require("../utils/logger.js");
39
+ /**
40
+ * @license
41
+ * Copyright 2025 Google LLC
42
+ * SPDX-License-Identifier: Apache-2.0
43
+ */
44
+ const GCP_PROJECT_ERROR_MESSAGE = "Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";
45
+ async function getGcpProjectId() {
46
+ try {
47
+ const auth = new import_google_auth_library.GoogleAuth();
48
+ const projectId = await auth.getProjectId();
49
+ return projectId || void 0;
50
+ } catch (error) {
51
+ return void 0;
52
+ }
53
+ }
54
+ async function getGcpExporters(config = {}) {
55
+ const {
56
+ enableTracing = false,
57
+ enableMetrics = false
58
+ // enableCloudLogging = false,
59
+ } = config;
60
+ const projectId = await getGcpProjectId();
61
+ if (!projectId) {
62
+ import_logger.logger.warn(GCP_PROJECT_ERROR_MESSAGE);
63
+ return {};
64
+ }
65
+ return {
66
+ spanProcessors: enableTracing ? [
67
+ new import_sdk_trace_base.BatchSpanProcessor(new import_opentelemetry_cloud_trace_exporter.TraceExporter({ projectId }))
68
+ ] : [],
69
+ metricReaders: enableMetrics ? [
70
+ new import_sdk_metrics.PeriodicExportingMetricReader({
71
+ exporter: new import_opentelemetry_cloud_monitoring_exporter.MetricExporter({ projectId }),
72
+ exportIntervalMillis: 5e3
73
+ })
74
+ ] : [],
75
+ logRecordProcessors: []
76
+ };
77
+ }
78
+ function getGcpResource() {
79
+ return (0, import_resources.detectResources)({ detectors: [import_resource_detector_gcp.gcpDetector] });
80
+ }
81
+ // Annotate the CommonJS export names for ESM import in node:
82
+ 0 && (module.exports = {
83
+ getGcpExporters,
84
+ getGcpResource
85
+ });
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+ var setup_exports = {};
26
+ __export(setup_exports, {
27
+ maybeSetOtelProviders: () => maybeSetOtelProviders
28
+ });
29
+ module.exports = __toCommonJS(setup_exports);
30
+ var import_api = require("@opentelemetry/api");
31
+ var import_api_logs = require("@opentelemetry/api-logs");
32
+ var import_sdk_logs = require("@opentelemetry/sdk-logs");
33
+ var import_sdk_metrics = require("@opentelemetry/sdk-metrics");
34
+ var import_resources = require("@opentelemetry/resources");
35
+ var import_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
36
+ var import_sdk_trace_node = require("@opentelemetry/sdk-trace-node");
37
+ var import_exporter_trace_otlp_http = require("@opentelemetry/exporter-trace-otlp-http");
38
+ var import_exporter_metrics_otlp_http = require("@opentelemetry/exporter-metrics-otlp-http");
39
+ var import_exporter_logs_otlp_http = require("@opentelemetry/exporter-logs-otlp-http");
40
+ /**
41
+ * @license
42
+ * Copyright 2025 Google LLC
43
+ * SPDX-License-Identifier: Apache-2.0
44
+ */
45
+ function maybeSetOtelProviders(otelHooksToSetup = [], otelResource) {
46
+ const resource = otelResource || getOtelResource();
47
+ const allHooks = [...otelHooksToSetup, getOtelExporters()];
48
+ const spanProcessors = allHooks.flatMap((hooks) => hooks.spanProcessors || []);
49
+ const metricReaders = allHooks.flatMap((hooks) => hooks.metricReaders || []);
50
+ const logRecordProcessors = allHooks.flatMap((hooks) => hooks.logRecordProcessors || []);
51
+ if (spanProcessors.length > 0) {
52
+ const tracerProvider = new import_sdk_trace_node.NodeTracerProvider({
53
+ resource,
54
+ spanProcessors
55
+ });
56
+ tracerProvider.register();
57
+ import_api.trace.setGlobalTracerProvider(tracerProvider);
58
+ }
59
+ if (metricReaders.length > 0) {
60
+ const meterProvider = new import_sdk_metrics.MeterProvider({
61
+ readers: metricReaders,
62
+ resource
63
+ });
64
+ import_api.metrics.setGlobalMeterProvider(meterProvider);
65
+ }
66
+ if (logRecordProcessors.length > 0) {
67
+ const loggerProvider = new import_sdk_logs.LoggerProvider({
68
+ resource,
69
+ processors: logRecordProcessors
70
+ });
71
+ import_api_logs.logs.setGlobalLoggerProvider(loggerProvider);
72
+ }
73
+ }
74
+ function getOtelResource() {
75
+ return (0, import_resources.detectResources)({
76
+ detectors: []
77
+ });
78
+ }
79
+ function getOtelExportersConfig() {
80
+ return {
81
+ enableTracing: !!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT),
82
+ enableMetrics: !!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT),
83
+ enableLogging: !!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)
84
+ };
85
+ }
86
+ function getOtelExporters(config = getOtelExportersConfig()) {
87
+ const { enableTracing, enableMetrics, enableLogging } = config;
88
+ return {
89
+ spanProcessors: enableTracing ? [new import_sdk_trace_base.BatchSpanProcessor(new import_exporter_trace_otlp_http.OTLPTraceExporter())] : [],
90
+ metricReaders: enableMetrics ? [new import_sdk_metrics.PeriodicExportingMetricReader({ exporter: new import_exporter_metrics_otlp_http.OTLPMetricExporter() })] : [],
91
+ logRecordProcessors: enableLogging ? [new import_sdk_logs.BatchLogRecordProcessor(new import_exporter_logs_otlp_http.OTLPLogExporter())] : []
92
+ };
93
+ }
94
+ // Annotate the CommonJS export names for ESM import in node:
95
+ 0 && (module.exports = {
96
+ maybeSetOtelProviders
97
+ });
@@ -0,0 +1,231 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+ var tracing_exports = {};
26
+ __export(tracing_exports, {
27
+ bindAsyncGenerator: () => bindAsyncGenerator,
28
+ traceAgentInvocation: () => traceAgentInvocation,
29
+ traceCallLlm: () => traceCallLlm,
30
+ traceMergedToolCalls: () => traceMergedToolCalls,
31
+ traceSendData: () => traceSendData,
32
+ traceToolCall: () => traceToolCall,
33
+ tracer: () => tracer
34
+ });
35
+ module.exports = __toCommonJS(tracing_exports);
36
+ var import_api = require("@opentelemetry/api");
37
+ var import_version = require("../version.js");
38
+ /**
39
+ * @license
40
+ * Copyright 2025 Google LLC
41
+ * SPDX-License-Identifier: Apache-2.0
42
+ */
43
+ const GEN_AI_AGENT_DESCRIPTION = "gen_ai.agent.description";
44
+ const GEN_AI_AGENT_NAME = "gen_ai.agent.name";
45
+ const GEN_AI_CONVERSATION_ID = "gen_ai.conversation.id";
46
+ const GEN_AI_OPERATION_NAME = "gen_ai.operation.name";
47
+ const GEN_AI_TOOL_CALL_ID = "gen_ai.tool.call.id";
48
+ const GEN_AI_TOOL_DESCRIPTION = "gen_ai.tool.description";
49
+ const GEN_AI_TOOL_NAME = "gen_ai.tool.name";
50
+ const GEN_AI_TOOL_TYPE = "gen_ai.tool.type";
51
+ const tracer = import_api.trace.getTracer(
52
+ "gcp.vertex.agent",
53
+ import_version.version
54
+ );
55
+ function safeJsonSerialize(obj) {
56
+ try {
57
+ return JSON.stringify(obj);
58
+ } catch (error) {
59
+ return "<not serializable>";
60
+ }
61
+ }
62
+ function traceAgentInvocation({
63
+ agent,
64
+ invocationContext
65
+ }) {
66
+ const span = import_api.trace.getActiveSpan();
67
+ if (!span) return;
68
+ span.setAttributes({
69
+ [GEN_AI_OPERATION_NAME]: "invoke_agent",
70
+ // Conditionally Required
71
+ [GEN_AI_AGENT_DESCRIPTION]: agent.description,
72
+ [GEN_AI_AGENT_NAME]: agent.name,
73
+ [GEN_AI_CONVERSATION_ID]: invocationContext.session.id
74
+ });
75
+ }
76
+ function traceToolCall({
77
+ tool,
78
+ args,
79
+ functionResponseEvent
80
+ }) {
81
+ var _a, _b;
82
+ const span = import_api.trace.getActiveSpan();
83
+ if (!span) return;
84
+ span.setAttributes({
85
+ [GEN_AI_OPERATION_NAME]: "execute_tool",
86
+ [GEN_AI_TOOL_DESCRIPTION]: tool.description || "",
87
+ [GEN_AI_TOOL_NAME]: tool.name,
88
+ // e.g. FunctionTool
89
+ [GEN_AI_TOOL_TYPE]: tool.constructor.name,
90
+ // Setting empty llm request and response (as UI expect these) while not
91
+ // applicable for tool_response.
92
+ "gcp.vertex.agent.llm_request": "{}",
93
+ "gcp.vertex.agent.llm_response": "{}",
94
+ "gcp.vertex.agent.tool_call_args": shouldAddRequestResponseToSpans() ? safeJsonSerialize(args) : "{}"
95
+ });
96
+ let toolCallId = "<not specified>";
97
+ let toolResponse = "<not specified>";
98
+ if ((_a = functionResponseEvent.content) == null ? void 0 : _a.parts) {
99
+ const responseParts = functionResponseEvent.content.parts;
100
+ const functionResponse = (_b = responseParts[0]) == null ? void 0 : _b.functionResponse;
101
+ if (functionResponse == null ? void 0 : functionResponse.id) {
102
+ toolCallId = functionResponse.id;
103
+ }
104
+ if (functionResponse == null ? void 0 : functionResponse.response) {
105
+ toolResponse = functionResponse.response;
106
+ }
107
+ }
108
+ if (typeof toolResponse !== "object" || toolResponse === null) {
109
+ toolResponse = { result: toolResponse };
110
+ }
111
+ span.setAttributes({
112
+ [GEN_AI_TOOL_CALL_ID]: toolCallId,
113
+ "gcp.vertex.agent.event_id": functionResponseEvent.id,
114
+ "gcp.vertex.agent.tool_response": shouldAddRequestResponseToSpans() ? safeJsonSerialize(toolResponse) : "{}"
115
+ });
116
+ }
117
+ function traceMergedToolCalls({
118
+ responseEventId,
119
+ functionResponseEvent
120
+ }) {
121
+ const span = import_api.trace.getActiveSpan();
122
+ if (!span) return;
123
+ span.setAttributes({
124
+ [GEN_AI_OPERATION_NAME]: "execute_tool",
125
+ [GEN_AI_TOOL_NAME]: "(merged tools)",
126
+ [GEN_AI_TOOL_DESCRIPTION]: "(merged tools)",
127
+ [GEN_AI_TOOL_CALL_ID]: responseEventId,
128
+ "gcp.vertex.agent.tool_call_args": "N/A",
129
+ "gcp.vertex.agent.event_id": responseEventId,
130
+ // Setting empty llm request and response (as UI expect these) while not
131
+ // applicable for tool_response.
132
+ "gcp.vertex.agent.llm_request": "{}",
133
+ "gcp.vertex.agent.llm_response": "{}"
134
+ });
135
+ span.setAttribute("gcp.vertex.agent.tool_response", shouldAddRequestResponseToSpans() ? safeJsonSerialize(functionResponseEvent) : "{}");
136
+ }
137
+ function traceCallLlm({
138
+ invocationContext,
139
+ eventId,
140
+ llmRequest,
141
+ llmResponse
142
+ }) {
143
+ var _a, _b, _c;
144
+ const span = import_api.trace.getActiveSpan();
145
+ if (!span) return;
146
+ span.setAttributes({
147
+ "gen_ai.system": "gcp.vertex.agent",
148
+ "gen_ai.request.model": llmRequest.model,
149
+ "gcp.vertex.agent.invocation_id": invocationContext.invocationId,
150
+ "gcp.vertex.agent.session_id": invocationContext.session.id,
151
+ "gcp.vertex.agent.event_id": eventId,
152
+ // Consider removing once GenAI SDK provides a way to record this info.
153
+ "gcp.vertex.agent.llm_request": shouldAddRequestResponseToSpans() ? safeJsonSerialize(buildLlmRequestForTrace(llmRequest)) : "{}"
154
+ });
155
+ if ((_a = llmRequest.config) == null ? void 0 : _a.topP) {
156
+ span.setAttribute("gen_ai.request.top_p", llmRequest.config.topP);
157
+ }
158
+ if (((_b = llmRequest.config) == null ? void 0 : _b.maxOutputTokens) !== void 0) {
159
+ span.setAttribute("gen_ai.request.max_tokens", llmRequest.config.maxOutputTokens);
160
+ }
161
+ span.setAttribute("gcp.vertex.agent.llm_response", shouldAddRequestResponseToSpans() ? safeJsonSerialize(llmResponse) : "{}");
162
+ if (llmResponse.usageMetadata) {
163
+ span.setAttribute("gen_ai.usage.input_tokens", llmResponse.usageMetadata.promptTokenCount || 0);
164
+ }
165
+ if ((_c = llmResponse.usageMetadata) == null ? void 0 : _c.candidatesTokenCount) {
166
+ span.setAttribute("gen_ai.usage.output_tokens", llmResponse.usageMetadata.candidatesTokenCount);
167
+ }
168
+ if (llmResponse.finishReason) {
169
+ const finishReasonValue = typeof llmResponse.finishReason === "string" ? llmResponse.finishReason.toLowerCase() : String(llmResponse.finishReason).toLowerCase();
170
+ span.setAttribute("gen_ai.response.finish_reasons", [finishReasonValue]);
171
+ }
172
+ }
173
+ function traceSendData({
174
+ invocationContext,
175
+ eventId,
176
+ data
177
+ }) {
178
+ const span = import_api.trace.getActiveSpan();
179
+ if (!span) return;
180
+ span.setAttributes({
181
+ "gcp.vertex.agent.invocation_id": invocationContext.invocationId,
182
+ "gcp.vertex.agent.event_id": eventId
183
+ });
184
+ span.setAttribute("gcp.vertex.agent.data", shouldAddRequestResponseToSpans() ? safeJsonSerialize(data) : "{}");
185
+ }
186
+ function buildLlmRequestForTrace(llmRequest) {
187
+ const result = {
188
+ model: llmRequest.model,
189
+ contents: []
190
+ };
191
+ if (llmRequest.config) {
192
+ const { responseSchema, ...cleanConfig } = llmRequest.config;
193
+ result.config = cleanConfig;
194
+ }
195
+ result.contents = llmRequest.contents.map((content) => {
196
+ var _a;
197
+ return {
198
+ role: content.role,
199
+ parts: ((_a = content.parts) == null ? void 0 : _a.filter((part) => !part.inlineData)) || []
200
+ };
201
+ });
202
+ return result;
203
+ }
204
+ function bindAsyncGenerator(ctx, generator) {
205
+ return {
206
+ // Bind the next() method to execute within the provided context
207
+ next: import_api.context.bind(ctx, generator.next.bind(generator)),
208
+ // Bind the return() method to execute within the provided context
209
+ return: import_api.context.bind(ctx, generator.return.bind(generator)),
210
+ // Bind the throw() method to execute within the provided context
211
+ throw: import_api.context.bind(ctx, generator.throw.bind(generator)),
212
+ // Ensure the async iterator symbol also returns a context-bound generator
213
+ [Symbol.asyncIterator]() {
214
+ return bindAsyncGenerator(ctx, generator[Symbol.asyncIterator]());
215
+ }
216
+ };
217
+ }
218
+ function shouldAddRequestResponseToSpans() {
219
+ const envValue = process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS || "true";
220
+ return envValue === "true" || envValue === "1";
221
+ }
222
+ // Annotate the CommonJS export names for ESM import in node:
223
+ 0 && (module.exports = {
224
+ bindAsyncGenerator,
225
+ traceAgentInvocation,
226
+ traceCallLlm,
227
+ traceMergedToolCalls,
228
+ traceSendData,
229
+ traceToolCall,
230
+ tracer
231
+ });
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+ var client_labels_exports = {};
26
+ __export(client_labels_exports, {
27
+ getClientLabels: () => getClientLabels
28
+ });
29
+ module.exports = __toCommonJS(client_labels_exports);
30
+ var import_version = require("../version.js");
31
+ var import_env_aware_utils = require("./env_aware_utils.js");
32
+ /**
33
+ * @license
34
+ * Copyright 2025 Google LLC
35
+ * SPDX-License-Identifier: Apache-2.0
36
+ */
37
+ const ADK_LABEL = "google-adk";
38
+ const LANGUAGE_LABEL = "gl-typescript";
39
+ const AGENT_ENGINE_TELEMETRY_TAG = "remote_reasoning_engine";
40
+ const AGENT_ENGINE_TELEMETRY_ENV_VARIABLE_NAME = "GOOGLE_CLOUD_AGENT_ENGINE_ID";
41
+ function _getDefaultLabels() {
42
+ let frameworkLabel = `${ADK_LABEL}/${import_version.version}`;
43
+ if (!(0, import_env_aware_utils.isBrowser)() && process.env[AGENT_ENGINE_TELEMETRY_ENV_VARIABLE_NAME]) {
44
+ frameworkLabel = `${frameworkLabel}+${AGENT_ENGINE_TELEMETRY_TAG}`;
45
+ }
46
+ const languageLabel = `${LANGUAGE_LABEL}/${(0, import_env_aware_utils.isBrowser)() ? window.navigator.userAgent : process.version}`;
47
+ return [frameworkLabel, languageLabel];
48
+ }
49
+ function getClientLabels() {
50
+ const labels = _getDefaultLabels();
51
+ return labels;
52
+ }
53
+ // Annotate the CommonJS export names for ESM import in node:
54
+ 0 && (module.exports = {
55
+ getClientLabels
56
+ });
@@ -32,7 +32,7 @@ module.exports = __toCommonJS(version_exports);
32
32
  * Copyright 2025 Google LLC
33
33
  * SPDX-License-Identifier: Apache-2.0
34
34
  */
35
- const version = "0.1.0";
35
+ const version = "0.2.0";
36
36
  // Annotate the CommonJS export names for ESM import in node:
37
37
  0 && (module.exports = {
38
38
  version
@@ -73,8 +73,8 @@ function isEventFromAnotherAgent(agentName, event) {
73
73
  return !!agentName && event.author !== agentName && event.author !== "user";
74
74
  }
75
75
  function convertForeignEvent(event) {
76
- var _a, _b, _c, _d, _e;
77
- if (!((_a = event.content) == null ? void 0 : _a.parts)) {
76
+ var _a, _b, _c, _d, _e, _f;
77
+ if (!((_b = (_a = event.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.length)) {
78
78
  return event;
79
79
  }
80
80
  const content = {
@@ -85,19 +85,21 @@ function convertForeignEvent(event) {
85
85
  };
86
86
  for (const part of event.content.parts) {
87
87
  if (part.text && !part.thought) {
88
- (_b = content.parts) == null ? void 0 : _b.push({
88
+ (_c = content.parts) == null ? void 0 : _c.push({
89
89
  text: `[${event.author}] said: ${part.text}`
90
90
  });
91
91
  } else if (part.functionCall) {
92
- (_c = content.parts) == null ? void 0 : _c.push({
93
- text: `[${event.author}] called tool \`${part.functionCall.name}\` with parameters: ${part.functionCall.args}`
92
+ const argsText = safeStringify(part.functionCall.args);
93
+ (_d = content.parts) == null ? void 0 : _d.push({
94
+ text: `[${event.author}] called tool \`${part.functionCall.name}\` with parameters: ${argsText}`
94
95
  });
95
96
  } else if (part.functionResponse) {
96
- (_d = content.parts) == null ? void 0 : _d.push({
97
- text: `[${event.author}] tool \`${part.functionResponse.name}\` returned result: ${part.functionResponse.response}`
97
+ const responseText = safeStringify(part.functionResponse.response);
98
+ (_e = content.parts) == null ? void 0 : _e.push({
99
+ text: `[${event.author}] tool \`${part.functionResponse.name}\` returned result: ${responseText}`
98
100
  });
99
101
  } else {
100
- (_e = content.parts) == null ? void 0 : _e.push(part);
102
+ (_f = content.parts) == null ? void 0 : _f.push(part);
101
103
  }
102
104
  }
103
105
  return createEvent({
@@ -262,6 +264,16 @@ function rearrangeEventsForAsyncFunctionResponsesInHistory(events) {
262
264
  }
263
265
  return resultEvents;
264
266
  }
267
+ function safeStringify(obj) {
268
+ if (typeof obj === "string") {
269
+ return obj;
270
+ }
271
+ try {
272
+ return JSON.stringify(obj);
273
+ } catch (e) {
274
+ return String(obj);
275
+ }
276
+ }
265
277
  export {
266
278
  getContents,
267
279
  getCurrentTurnContents