@google/adk 0.2.5 → 0.3.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 (166) hide show
  1. package/dist/cjs/agents/base_agent.js +43 -21
  2. package/dist/cjs/agents/callback_context.js +4 -1
  3. package/dist/cjs/agents/content_processor_utils.js +15 -7
  4. package/dist/cjs/agents/functions.js +79 -29
  5. package/dist/cjs/agents/llm_agent.js +59 -33
  6. package/dist/cjs/agents/loop_agent.js +2 -1
  7. package/dist/cjs/agents/parallel_agent.js +3 -4
  8. package/dist/cjs/artifacts/gcs_artifact_service.js +28 -20
  9. package/dist/cjs/artifacts/in_memory_artifact_service.js +18 -4
  10. package/dist/cjs/auth/auth_handler.js +3 -1
  11. package/dist/cjs/code_executors/base_code_executor.js +3 -1
  12. package/dist/cjs/code_executors/built_in_code_executor.js +7 -3
  13. package/dist/cjs/code_executors/code_executor_context.js +5 -5
  14. package/dist/cjs/common.js +4 -0
  15. package/dist/cjs/events/event.js +1 -3
  16. package/dist/cjs/index.js +19 -19
  17. package/dist/cjs/index.js.map +4 -4
  18. package/dist/cjs/memory/in_memory_memory_service.js +3 -1
  19. package/dist/cjs/models/base_llm.js +8 -4
  20. package/dist/cjs/models/gemini_llm_connection.js +1 -0
  21. package/dist/cjs/models/google_llm.js +3 -3
  22. package/dist/cjs/plugins/base_plugin.js +12 -0
  23. package/dist/cjs/plugins/logging_plugin.js +50 -13
  24. package/dist/cjs/plugins/plugin_manager.js +56 -24
  25. package/dist/cjs/plugins/security_plugin.js +1 -1
  26. package/dist/cjs/runner/runner.js +110 -95
  27. package/dist/cjs/sessions/in_memory_session_service.js +38 -14
  28. package/dist/cjs/telemetry/google_cloud.js +7 -9
  29. package/dist/cjs/telemetry/setup.js +15 -7
  30. package/dist/cjs/telemetry/tracing.js +37 -15
  31. package/dist/cjs/tools/agent_tool.js +8 -4
  32. package/dist/cjs/tools/base_tool.js +4 -2
  33. package/dist/cjs/tools/forwarding_artifact_service.js +1 -1
  34. package/dist/cjs/tools/function_tool.js +1 -2
  35. package/dist/cjs/tools/google_search_tool.js +1 -2
  36. package/dist/cjs/tools/mcp/mcp_session_manager.js +16 -10
  37. package/dist/cjs/tools/mcp/mcp_tool.js +1 -3
  38. package/dist/cjs/tools/mcp/mcp_toolset.js +1 -1
  39. package/dist/cjs/utils/env_aware_utils.js +1 -1
  40. package/dist/cjs/utils/gemini_schema_util.js +9 -4
  41. package/dist/cjs/utils/logger.js +47 -3
  42. package/dist/cjs/utils/simple_zod_to_json.js +100 -141
  43. package/dist/cjs/utils/variant_utils.js +1 -1
  44. package/dist/cjs/version.js +1 -1
  45. package/dist/esm/agents/base_agent.js +48 -22
  46. package/dist/esm/agents/callback_context.js +4 -1
  47. package/dist/esm/agents/content_processor_utils.js +25 -9
  48. package/dist/esm/agents/functions.js +83 -29
  49. package/dist/esm/agents/llm_agent.js +63 -33
  50. package/dist/esm/agents/loop_agent.js +2 -1
  51. package/dist/esm/agents/parallel_agent.js +3 -4
  52. package/dist/esm/artifacts/gcs_artifact_service.js +28 -20
  53. package/dist/esm/artifacts/in_memory_artifact_service.js +18 -4
  54. package/dist/esm/auth/auth_handler.js +3 -1
  55. package/dist/esm/code_executors/base_code_executor.js +3 -1
  56. package/dist/esm/code_executors/built_in_code_executor.js +7 -3
  57. package/dist/esm/code_executors/code_executor_context.js +5 -5
  58. package/dist/esm/common.js +3 -1
  59. package/dist/esm/events/event.js +1 -3
  60. package/dist/esm/index.js +19 -19
  61. package/dist/esm/index.js.map +4 -4
  62. package/dist/esm/memory/in_memory_memory_service.js +3 -1
  63. package/dist/esm/models/base_llm.js +8 -4
  64. package/dist/esm/models/gemini_llm_connection.js +1 -0
  65. package/dist/esm/models/google_llm.js +8 -4
  66. package/dist/esm/plugins/base_plugin.js +12 -0
  67. package/dist/esm/plugins/logging_plugin.js +55 -14
  68. package/dist/esm/plugins/plugin_manager.js +56 -24
  69. package/dist/esm/plugins/security_plugin.js +1 -1
  70. package/dist/esm/runner/runner.js +114 -96
  71. package/dist/esm/sessions/in_memory_session_service.js +41 -15
  72. package/dist/esm/telemetry/google_cloud.js +7 -9
  73. package/dist/esm/telemetry/setup.js +23 -9
  74. package/dist/esm/telemetry/tracing.js +37 -15
  75. package/dist/esm/tools/agent_tool.js +8 -4
  76. package/dist/esm/tools/base_tool.js +4 -2
  77. package/dist/esm/tools/forwarding_artifact_service.js +1 -1
  78. package/dist/esm/tools/function_tool.js +1 -2
  79. package/dist/esm/tools/google_search_tool.js +2 -5
  80. package/dist/esm/tools/long_running_tool.js +3 -1
  81. package/dist/esm/tools/mcp/mcp_session_manager.js +22 -12
  82. package/dist/esm/tools/mcp/mcp_tool.js +1 -3
  83. package/dist/esm/tools/mcp/mcp_toolset.js +1 -1
  84. package/dist/esm/utils/env_aware_utils.js +1 -1
  85. package/dist/esm/utils/gemini_schema_util.js +9 -4
  86. package/dist/esm/utils/logger.js +43 -2
  87. package/dist/esm/utils/simple_zod_to_json.js +102 -141
  88. package/dist/esm/utils/variant_utils.js +1 -1
  89. package/dist/esm/version.js +1 -1
  90. package/dist/types/agents/base_agent.d.ts +2 -1
  91. package/dist/types/agents/callback_context.d.ts +1 -1
  92. package/dist/types/agents/llm_agent.d.ts +1 -1
  93. package/dist/types/agents/loop_agent.d.ts +1 -1
  94. package/dist/types/agents/parallel_agent.d.ts +1 -1
  95. package/dist/types/artifacts/in_memory_artifact_service.d.ts +3 -3
  96. package/dist/types/code_executors/built_in_code_executor.d.ts +1 -1
  97. package/dist/types/code_executors/code_executor_context.d.ts +2 -4
  98. package/dist/types/common.d.ts +2 -1
  99. package/dist/types/index.d.ts +3 -3
  100. package/dist/types/models/base_llm_connection.d.ts +1 -1
  101. package/dist/types/models/llm_response.d.ts +1 -1
  102. package/dist/types/plugins/logging_plugin.d.ts +12 -12
  103. package/dist/types/plugins/plugin_manager.d.ts +12 -12
  104. package/dist/types/plugins/security_plugin.d.ts +1 -1
  105. package/dist/types/runner/runner.d.ts +1 -1
  106. package/dist/types/sessions/in_memory_session_service.d.ts +5 -5
  107. package/dist/types/telemetry/setup.d.ts +1 -1
  108. package/dist/types/telemetry/tracing.d.ts +7 -6
  109. package/dist/types/tools/agent_tool.d.ts +1 -1
  110. package/dist/types/tools/base_tool.d.ts +1 -1
  111. package/dist/types/tools/base_toolset.d.ts +2 -1
  112. package/dist/types/tools/forwarding_artifact_service.d.ts +2 -2
  113. package/dist/types/tools/function_tool.d.ts +4 -3
  114. package/dist/types/tools/google_search_tool.d.ts +3 -3
  115. package/dist/types/tools/mcp/mcp_session_manager.d.ts +10 -3
  116. package/dist/types/tools/mcp/mcp_toolset.d.ts +1 -2
  117. package/dist/types/utils/gemini_schema_util.d.ts +4 -12
  118. package/dist/types/utils/logger.d.ts +11 -10
  119. package/dist/types/utils/simple_zod_to_json.d.ts +5 -4
  120. package/dist/types/version.d.ts +1 -1
  121. package/dist/web/agents/base_agent.js +94 -33
  122. package/dist/web/agents/callback_context.js +4 -1
  123. package/dist/web/agents/content_processor_utils.js +25 -9
  124. package/dist/web/agents/functions.js +83 -29
  125. package/dist/web/agents/llm_agent.js +117 -54
  126. package/dist/web/agents/loop_agent.js +2 -1
  127. package/dist/web/agents/parallel_agent.js +3 -4
  128. package/dist/web/artifacts/gcs_artifact_service.js +25 -17
  129. package/dist/web/artifacts/in_memory_artifact_service.js +18 -4
  130. package/dist/web/auth/auth_handler.js +3 -1
  131. package/dist/web/code_executors/base_code_executor.js +3 -1
  132. package/dist/web/code_executors/built_in_code_executor.js +7 -3
  133. package/dist/web/code_executors/code_executor_context.js +5 -5
  134. package/dist/web/common.js +3 -1
  135. package/dist/web/events/event.js +1 -3
  136. package/dist/web/index.js +1 -1
  137. package/dist/web/index.js.map +4 -4
  138. package/dist/web/memory/in_memory_memory_service.js +3 -1
  139. package/dist/web/models/base_llm.js +8 -4
  140. package/dist/web/models/gemini_llm_connection.js +1 -0
  141. package/dist/web/models/google_llm.js +8 -4
  142. package/dist/web/plugins/base_plugin.js +12 -0
  143. package/dist/web/plugins/logging_plugin.js +55 -14
  144. package/dist/web/plugins/plugin_manager.js +56 -24
  145. package/dist/web/plugins/security_plugin.js +1 -1
  146. package/dist/web/runner/runner.js +159 -108
  147. package/dist/web/sessions/in_memory_session_service.js +41 -15
  148. package/dist/web/telemetry/google_cloud.js +7 -9
  149. package/dist/web/telemetry/setup.js +23 -9
  150. package/dist/web/telemetry/tracing.js +37 -15
  151. package/dist/web/tools/agent_tool.js +8 -4
  152. package/dist/web/tools/base_tool.js +4 -2
  153. package/dist/web/tools/forwarding_artifact_service.js +1 -1
  154. package/dist/web/tools/function_tool.js +1 -2
  155. package/dist/web/tools/google_search_tool.js +2 -5
  156. package/dist/web/tools/long_running_tool.js +3 -1
  157. package/dist/web/tools/mcp/mcp_session_manager.js +22 -12
  158. package/dist/web/tools/mcp/mcp_tool.js +1 -3
  159. package/dist/web/tools/mcp/mcp_toolset.js +1 -1
  160. package/dist/web/utils/env_aware_utils.js +1 -1
  161. package/dist/web/utils/gemini_schema_util.js +9 -4
  162. package/dist/web/utils/logger.js +43 -2
  163. package/dist/web/utils/simple_zod_to_json.js +102 -155
  164. package/dist/web/utils/variant_utils.js +1 -1
  165. package/dist/web/version.js +1 -1
  166. package/package.json +4 -2
@@ -31,6 +31,7 @@ __export(base_agent_exports, {
31
31
  module.exports = __toCommonJS(base_agent_exports);
32
32
  var import_api = require("@opentelemetry/api");
33
33
  var import_event = require("../events/event.js");
34
+ var import_tracing = require("../telemetry/tracing.js");
34
35
  var import_callback_context = require("./callback_context.js");
35
36
  var import_invocation_context = require("./invocation_context.js");
36
37
  /**
@@ -54,13 +55,19 @@ class BaseAgent {
54
55
  this.description = config.description;
55
56
  this.parentAgent = config.parentAgent;
56
57
  this.subAgents = config.subAgents || [];
57
- this.rootAgent = getRootAgent(this);
58
58
  this.beforeAgentCallback = getCannonicalCallback(
59
59
  config.beforeAgentCallback
60
60
  );
61
61
  this.afterAgentCallback = getCannonicalCallback(config.afterAgentCallback);
62
62
  this.setParentAgentForSubAgents();
63
63
  }
64
+ /**
65
+ * Root agent of this agent.
66
+ * Computed dynamically by traversing up the parent chain.
67
+ */
68
+ get rootAgent() {
69
+ return getRootAgent(this);
70
+ }
64
71
  /**
65
72
  * Entry method to run an agent via text-based conversation.
66
73
  *
@@ -69,26 +76,34 @@ class BaseAgent {
69
76
  * @returns An AsyncGenerator that yields the events generated by the agent.
70
77
  */
71
78
  async *runAsync(parentContext) {
72
- const span = import_api.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);
79
+ const span = import_tracing.tracer.startSpan(`invoke_agent ${this.name}`);
80
+ const ctx = import_api.trace.setSpan(import_api.context.active(), span);
73
81
  try {
74
- const context = this.createInvocationContext(parentContext);
75
- const beforeAgentCallbackEvent = await this.handleBeforeAgentCallback(context);
76
- if (beforeAgentCallbackEvent) {
77
- yield beforeAgentCallbackEvent;
78
- }
79
- if (context.endInvocation) {
80
- return;
81
- }
82
- for await (const event of this.runAsyncImpl(context)) {
83
- yield event;
84
- }
85
- if (context.endInvocation) {
86
- return;
87
- }
88
- const afterAgentCallbackEvent = await this.handleAfterAgentCallback(context);
89
- if (afterAgentCallbackEvent) {
90
- yield afterAgentCallbackEvent;
91
- }
82
+ yield* (0, import_tracing.runAsyncGeneratorWithOtelContext)(
83
+ ctx,
84
+ this,
85
+ async function* () {
86
+ const context2 = this.createInvocationContext(parentContext);
87
+ const beforeAgentCallbackEvent = await this.handleBeforeAgentCallback(context2);
88
+ if (beforeAgentCallbackEvent) {
89
+ yield beforeAgentCallbackEvent;
90
+ }
91
+ if (context2.endInvocation) {
92
+ return;
93
+ }
94
+ (0, import_tracing.traceAgentInvocation)({ agent: this, invocationContext: context2 });
95
+ for await (const event of this.runAsyncImpl(context2)) {
96
+ yield event;
97
+ }
98
+ if (context2.endInvocation) {
99
+ return;
100
+ }
101
+ const afterAgentCallbackEvent = await this.handleAfterAgentCallback(context2);
102
+ if (afterAgentCallbackEvent) {
103
+ yield afterAgentCallbackEvent;
104
+ }
105
+ }
106
+ );
92
107
  } finally {
93
108
  span.end();
94
109
  }
@@ -101,8 +116,15 @@ class BaseAgent {
101
116
  * @returns An AsyncGenerator that yields the events generated by the agent.
102
117
  */
103
118
  async *runLive(parentContext) {
104
- const span = import_api.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);
119
+ const span = import_tracing.tracer.startSpan(`invoke_agent ${this.name}`);
120
+ const ctx = import_api.trace.setSpan(import_api.context.active(), span);
105
121
  try {
122
+ yield* (0, import_tracing.runAsyncGeneratorWithOtelContext)(
123
+ ctx,
124
+ this,
125
+ async function* () {
126
+ }
127
+ );
106
128
  throw new Error("Live mode is not implemented yet.");
107
129
  } finally {
108
130
  span.end();
@@ -36,7 +36,10 @@ var import_readonly_context = require("./readonly_context.js");
36
36
  * SPDX-License-Identifier: Apache-2.0
37
37
  */
38
38
  class CallbackContext extends import_readonly_context.ReadonlyContext {
39
- constructor({ invocationContext, eventActions }) {
39
+ constructor({
40
+ invocationContext,
41
+ eventActions
42
+ }) {
40
43
  super(invocationContext);
41
44
  this.eventActions = eventActions || (0, import_event_actions.createEventActions)();
42
45
  this._state = new import_state.State(
@@ -109,9 +109,11 @@ function convertForeignEvent(event) {
109
109
  }
110
110
  const content = {
111
111
  role: "user",
112
- parts: [{
113
- text: "For context:"
114
- }]
112
+ parts: [
113
+ {
114
+ text: "For context:"
115
+ }
116
+ ]
115
117
  };
116
118
  for (const part of event.content.parts) {
117
119
  if (part.text && !part.thought) {
@@ -213,10 +215,14 @@ function rearrangeEventsForLatestFunctionResponse(events) {
213
215
  const functionCallIds = new Set(
214
216
  functionCalls.map((fc) => fc.id).filter((id) => !!id)
215
217
  );
216
- const isSubset = Array.from(functionResponsesIds).every((id) => functionCallIds.has(id));
218
+ const isSubset = Array.from(functionResponsesIds).every(
219
+ (id) => functionCallIds.has(id)
220
+ );
217
221
  if (!isSubset) {
218
222
  throw new Error(
219
- `Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(functionCallIds).join(", ")}, function response ids provided: ${Array.from(functionResponsesIds).join(", ")}`
223
+ `Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(functionCallIds).join(
224
+ ", "
225
+ )}, function response ids provided: ${Array.from(functionResponsesIds).join(", ")}`
220
226
  );
221
227
  }
222
228
  functionResponsesIds = functionCallIds;
@@ -284,7 +290,9 @@ function rearrangeEventsForAsyncFunctionResponsesInHistory(events) {
284
290
  const [responseIndex] = [...functionResponseEventsIndices];
285
291
  resultEvents.push(events[responseIndex]);
286
292
  } else {
287
- const indicesArray = Array.from(functionResponseEventsIndices).sort((a, b) => a - b);
293
+ const indicesArray = Array.from(functionResponseEventsIndices).sort(
294
+ (a, b) => a - b
295
+ );
288
296
  const eventsToMerge = indicesArray.map((index) => events[index]);
289
297
  resultEvents.push(mergeFunctionResponseEvents(eventsToMerge));
290
298
  }
@@ -300,7 +308,7 @@ function safeStringify(obj) {
300
308
  }
301
309
  try {
302
310
  return JSON.stringify(obj);
303
- } catch (e) {
311
+ } catch (_e) {
304
312
  return String(obj);
305
313
  }
306
314
  }
@@ -45,6 +45,7 @@ var import_event_actions = require("../events/event_actions.js");
45
45
  var import_tool_context = require("../tools/tool_context.js");
46
46
  var import_env_aware_utils = require("../utils/env_aware_utils.js");
47
47
  var import_logger = require("../utils/logger.js");
48
+ var import_tracing = require("../telemetry/tracing.js");
48
49
  /**
49
50
  * @license
50
51
  * Copyright 2025 Google LLC
@@ -167,8 +168,51 @@ function generateRequestConfirmationEvent({
167
168
  });
168
169
  }
169
170
  async function callToolAsync(tool, args, toolContext) {
170
- import_logger.logger.debug(`callToolAsync ${tool.name}`);
171
- return await tool.runAsync({ args, toolContext });
171
+ return import_tracing.tracer.startActiveSpan(`execute_tool ${tool.name}`, async (span) => {
172
+ try {
173
+ import_logger.logger.debug(`callToolAsync ${tool.name}`);
174
+ const result = await tool.runAsync({ args, toolContext });
175
+ (0, import_tracing.traceToolCall)({
176
+ tool,
177
+ args,
178
+ functionResponseEvent: buildResponseEvent(
179
+ tool,
180
+ result,
181
+ toolContext,
182
+ toolContext.invocationContext
183
+ )
184
+ });
185
+ return result;
186
+ } finally {
187
+ span.end();
188
+ }
189
+ });
190
+ }
191
+ function buildResponseEvent(tool, functionResult, toolContext, invocationContext) {
192
+ let responseResult;
193
+ if (typeof functionResult !== "object" || functionResult == null) {
194
+ responseResult = { result: functionResult };
195
+ } else {
196
+ responseResult = functionResult;
197
+ }
198
+ const partFunctionResponse = {
199
+ functionResponse: {
200
+ name: tool.name,
201
+ response: responseResult,
202
+ id: toolContext.functionCallId
203
+ }
204
+ };
205
+ const content = {
206
+ role: "user",
207
+ parts: [partFunctionResponse]
208
+ };
209
+ return (0, import_event.createEvent)({
210
+ invocationId: invocationContext.invocationId,
211
+ author: invocationContext.agent.name,
212
+ content,
213
+ actions: toolContext.actions,
214
+ branch: invocationContext.branch
215
+ });
172
216
  }
173
217
  async function handleFunctionCallsAsync({
174
218
  invocationContext,
@@ -209,14 +253,12 @@ async function handleFunctionCallList({
209
253
  if (toolConfirmationDict && functionCall.id) {
210
254
  toolConfirmation = toolConfirmationDict[functionCall.id];
211
255
  }
212
- const { tool, toolContext } = getToolAndContext(
213
- {
214
- invocationContext,
215
- functionCall,
216
- toolsDict,
217
- toolConfirmation
218
- }
219
- );
256
+ const { tool, toolContext } = getToolAndContext({
257
+ invocationContext,
258
+ functionCall,
259
+ toolsDict,
260
+ toolConfirmation
261
+ });
220
262
  import_logger.logger.debug(`execute_tool ${tool.name}`);
221
263
  const functionArgs = (_a = functionCall.args) != null ? _a : {};
222
264
  let functionResponse = null;
@@ -240,21 +282,15 @@ async function handleFunctionCallList({
240
282
  }
241
283
  if (functionResponse == null) {
242
284
  try {
243
- functionResponse = await callToolAsync(
244
- tool,
245
- functionArgs,
246
- toolContext
247
- );
285
+ functionResponse = await callToolAsync(tool, functionArgs, toolContext);
248
286
  } catch (e) {
249
287
  if (e instanceof Error) {
250
- const onToolErrorResponse = await invocationContext.pluginManager.runOnToolErrorCallback(
251
- {
252
- tool,
253
- toolArgs: functionArgs,
254
- toolContext,
255
- error: e
256
- }
257
- );
288
+ const onToolErrorResponse = await invocationContext.pluginManager.runOnToolErrorCallback({
289
+ tool,
290
+ toolArgs: functionArgs,
291
+ toolContext,
292
+ error: e
293
+ });
258
294
  if (onToolErrorResponse) {
259
295
  functionResponse = onToolErrorResponse;
260
296
  } else {
@@ -318,12 +354,24 @@ async function handleFunctionCallList({
318
354
  if (!functionResponseEvents.length) {
319
355
  return null;
320
356
  }
321
- const mergedEvent = mergeParallelFunctionResponseEvents(functionResponseEvents);
357
+ const mergedEvent = mergeParallelFunctionResponseEvents(
358
+ functionResponseEvents
359
+ );
322
360
  if (functionResponseEvents.length > 1) {
323
- import_logger.logger.debug("execute_tool (merged)");
324
- import_logger.logger.debug("traceMergedToolCalls", {
325
- responseEventId: mergedEvent.id,
326
- functionResponseEvent: mergedEvent.id
361
+ import_tracing.tracer.startActiveSpan("execute_tool (merged)", (span) => {
362
+ try {
363
+ import_logger.logger.debug("execute_tool (merged)");
364
+ import_logger.logger.debug("traceMergedToolCalls", {
365
+ responseEventId: mergedEvent.id,
366
+ functionResponseEvent: mergedEvent.id
367
+ });
368
+ (0, import_tracing.traceMergedToolCalls)({
369
+ responseEventId: mergedEvent.id,
370
+ functionResponseEvent: mergedEvent
371
+ });
372
+ } finally {
373
+ span.end();
374
+ }
327
375
  });
328
376
  }
329
377
  return mergedEvent;
@@ -361,7 +409,9 @@ function mergeParallelFunctionResponseEvents(functionResponseEvents) {
361
409
  }
362
410
  }
363
411
  const baseEvent = functionResponseEvents[0];
364
- const actionsList = functionResponseEvents.map((event) => event.actions || {});
412
+ const actionsList = functionResponseEvents.map(
413
+ (event) => event.actions || {}
414
+ );
365
415
  const mergedActions = (0, import_event_actions.mergeEventActions)(actionsList);
366
416
  return (0, import_event.createEvent)({
367
417
  author: baseEvent.author,
@@ -30,6 +30,7 @@ __export(llm_agent_exports, {
30
30
  responseProcessor: () => responseProcessor
31
31
  });
32
32
  module.exports = __toCommonJS(llm_agent_exports);
33
+ var import_api = require("@opentelemetry/api");
33
34
  var import_lodash_es = require("lodash-es");
34
35
  var import_zod = require("zod");
35
36
  var import_base_code_executor = require("../code_executors/base_code_executor.js");
@@ -48,6 +49,7 @@ var import_tool_confirmation = require("../tools/tool_confirmation.js");
48
49
  var import_tool_context = require("../tools/tool_context.js");
49
50
  var import_env_aware_utils = require("../utils/env_aware_utils.js");
50
51
  var import_logger = require("../utils/logger.js");
52
+ var import_tracing = require("../telemetry/tracing.js");
51
53
  var import_base_agent = require("./base_agent.js");
52
54
  var import_base_llm_processor = require("./base_llm_processor.js");
53
55
  var import_callback_context = require("./callback_context.js");
@@ -63,13 +65,14 @@ var import_run_config = require("./run_config.js");
63
65
  */
64
66
  var _a, _b;
65
67
  const ADK_AGENT_NAME_LABEL_KEY = "adk_agent_name";
66
- async function convertToolUnionToTools(toolUnion, context) {
68
+ async function convertToolUnionToTools(toolUnion, context2) {
67
69
  if (toolUnion instanceof import_base_tool.BaseTool) {
68
70
  return [toolUnion];
69
71
  }
70
- return await toolUnion.getTools(context);
72
+ return await toolUnion.getTools(context2);
71
73
  }
72
74
  class BasicLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
75
+ // eslint-disable-next-line require-yield
73
76
  async *runAsync(invocationContext, llmRequest) {
74
77
  var _a2;
75
78
  const agent = invocationContext.agent;
@@ -94,6 +97,7 @@ class BasicLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestP
94
97
  }
95
98
  const BASIC_LLM_REQUEST_PROCESSOR = new BasicLlmRequestProcessor();
96
99
  class IdentityLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
100
+ // eslint-disable-next-line require-yield
97
101
  async *runAsync(invocationContext, llmRequest) {
98
102
  const agent = invocationContext.agent;
99
103
  const si = [`You are an agent. Your internal name is "${agent.name}".`];
@@ -108,6 +112,7 @@ class InstructionsLlmRequestProcessor extends import_base_llm_processor.BaseLlmR
108
112
  /**
109
113
  * Handles instructions and global instructions for LLM flow.
110
114
  */
115
+ // eslint-disable-next-line require-yield
111
116
  async *runAsync(invocationContext, llmRequest) {
112
117
  const agent = invocationContext.agent;
113
118
  if (!(agent instanceof LlmAgent) || !(agent.rootAgent instanceof LlmAgent)) {
@@ -144,6 +149,7 @@ class InstructionsLlmRequestProcessor extends import_base_llm_processor.BaseLlmR
144
149
  }
145
150
  const INSTRUCTIONS_LLM_REQUEST_PROCESSOR = new InstructionsLlmRequestProcessor();
146
151
  class ContentRequestProcessor {
152
+ // eslint-disable-next-line require-yield
147
153
  async *runAsync(invocationContext, llmRequest) {
148
154
  const agent = invocationContext.agent;
149
155
  if (!agent || !isLlmAgent(agent)) {
@@ -185,6 +191,7 @@ class AgentTransferLlmRequestProcessor extends import_base_llm_processor.BaseLlm
185
191
  }
186
192
  });
187
193
  }
194
+ // eslint-disable-next-line require-yield
188
195
  async *runAsync(invocationContext, llmRequest) {
189
196
  if (!(invocationContext.agent instanceof LlmAgent)) {
190
197
  return;
@@ -253,7 +260,7 @@ to your parent agent.
253
260
  const AGENT_TRANSFER_LLM_REQUEST_PROCESSOR = new AgentTransferLlmRequestProcessor();
254
261
  class RequestConfirmationLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
255
262
  /** Handles tool confirmation information to build the LLM request. */
256
- async *runAsync(invocationContext, llmRequest) {
263
+ async *runAsync(invocationContext) {
257
264
  const agent = invocationContext.agent;
258
265
  if (!isLlmAgent(agent)) {
259
266
  return;
@@ -386,7 +393,7 @@ class CodeExecutionRequestProcessor extends import_base_llm_processor.BaseLlmReq
386
393
  }
387
394
  for (const content of llmRequest.contents) {
388
395
  const delimeters = invocationContext.agent.codeExecutor.codeBlockDelimiters.length ? invocationContext.agent.codeExecutor.codeBlockDelimiters[0] : ["", ""];
389
- const codeExecutionParts = (0, import_code_execution_utils.convertCodeExecutionParts)(
396
+ (0, import_code_execution_utils.convertCodeExecutionParts)(
390
397
  content,
391
398
  delimeters,
392
399
  invocationContext.agent.codeExecutor.executionResultDelimiters
@@ -596,7 +603,7 @@ async function* runPostProcessor(invocationContext, llmResponse) {
596
603
  codeExecutorContext,
597
604
  codeExecutionResult
598
605
  );
599
- llmResponse.content = null;
606
+ llmResponse.content = void 0;
600
607
  }
601
608
  function extractAndReplaceInlineFiles(codeExecutorContext, llmRequest) {
602
609
  var _a2;
@@ -809,12 +816,12 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
809
816
  * @param context The context to retrieve the session state.
810
817
  * @returns The resolved instruction field.
811
818
  */
812
- async canonicalInstruction(context) {
819
+ async canonicalInstruction(context2) {
813
820
  if (typeof this.instruction === "string") {
814
821
  return { instruction: this.instruction, requireStateInjection: true };
815
822
  }
816
823
  return {
817
- instruction: await this.instruction(context),
824
+ instruction: await this.instruction(context2),
818
825
  requireStateInjection: false
819
826
  };
820
827
  }
@@ -825,12 +832,15 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
825
832
  * @param context The context to retrieve the session state.
826
833
  * @returns The resolved globalInstruction field.
827
834
  */
828
- async canonicalGlobalInstruction(context) {
835
+ async canonicalGlobalInstruction(context2) {
829
836
  if (typeof this.globalInstruction === "string") {
830
- return { instruction: this.globalInstruction, requireStateInjection: true };
837
+ return {
838
+ instruction: this.globalInstruction,
839
+ requireStateInjection: true
840
+ };
831
841
  }
832
842
  return {
833
- instruction: await this.globalInstruction(context),
843
+ instruction: await this.globalInstruction(context2),
834
844
  requireStateInjection: false
835
845
  };
836
846
  }
@@ -839,10 +849,10 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
839
849
  *
840
850
  * This method is only for use by Agent Development Kit.
841
851
  */
842
- async canonicalTools(context) {
852
+ async canonicalTools(context2) {
843
853
  const resolvedTools = [];
844
854
  for (const toolUnion of this.tools) {
845
- const tools = await convertToolUnionToTools(toolUnion, context);
855
+ const tools = await convertToolUnionToTools(toolUnion, context2);
846
856
  resolvedTools.push(...tools);
847
857
  }
848
858
  return resolvedTools;
@@ -946,10 +956,10 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
946
956
  }
947
957
  event.actions.stateDelta[this.outputKey] = result;
948
958
  }
949
- async *runAsyncImpl(context) {
959
+ async *runAsyncImpl(context2) {
950
960
  while (true) {
951
961
  let lastEvent = void 0;
952
- for await (const event of this.runOneStepAsync(context)) {
962
+ for await (const event of this.runOneStepAsync(context2)) {
953
963
  lastEvent = event;
954
964
  this.maybeSaveOutputToState(event);
955
965
  yield event;
@@ -963,19 +973,20 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
963
973
  }
964
974
  }
965
975
  }
966
- async *runLiveImpl(context) {
967
- for await (const event of this.runLiveFlow(context)) {
976
+ async *runLiveImpl(context2) {
977
+ for await (const event of this.runLiveFlow(context2)) {
968
978
  this.maybeSaveOutputToState(event);
969
979
  yield event;
970
980
  }
971
- if (context.endInvocation) {
981
+ if (context2.endInvocation) {
972
982
  return;
973
983
  }
974
984
  }
975
985
  // --------------------------------------------------------------------------
976
986
  // #START LlmFlow Logic
977
987
  // --------------------------------------------------------------------------
978
- async *runLiveFlow(invocationContext) {
988
+ // eslint-disable-next-line require-yield
989
+ async *runLiveFlow(_invocationContext) {
979
990
  await Promise.resolve();
980
991
  throw new Error("LlmAgent.runLiveFlow not implemented");
981
992
  }
@@ -1011,22 +1022,31 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1011
1022
  author: this.name,
1012
1023
  branch: invocationContext.branch
1013
1024
  });
1014
- for await (const llmResponse of this.callLlmAsync(
1015
- invocationContext,
1016
- llmRequest,
1017
- modelResponseEvent
1018
- )) {
1019
- for await (const event of this.postprocess(
1020
- invocationContext,
1021
- llmRequest,
1022
- llmResponse,
1023
- modelResponseEvent
1024
- )) {
1025
- modelResponseEvent.id = (0, import_event.createNewEventId)();
1026
- modelResponseEvent.timestamp = (/* @__PURE__ */ new Date()).getTime();
1027
- yield event;
1025
+ const span = import_tracing.tracer.startSpan("call_llm");
1026
+ const ctx = import_api.trace.setSpan(import_api.context.active(), span);
1027
+ yield* (0, import_tracing.runAsyncGeneratorWithOtelContext)(
1028
+ ctx,
1029
+ this,
1030
+ async function* () {
1031
+ for await (const llmResponse of this.callLlmAsync(
1032
+ invocationContext,
1033
+ llmRequest,
1034
+ modelResponseEvent
1035
+ )) {
1036
+ for await (const event of this.postprocess(
1037
+ invocationContext,
1038
+ llmRequest,
1039
+ llmResponse,
1040
+ modelResponseEvent
1041
+ )) {
1042
+ modelResponseEvent.id = (0, import_event.createNewEventId)();
1043
+ modelResponseEvent.timestamp = (/* @__PURE__ */ new Date()).getTime();
1044
+ yield event;
1045
+ }
1046
+ }
1028
1047
  }
1029
- }
1048
+ );
1049
+ span.end();
1030
1050
  }
1031
1051
  async *postprocess(invocationContext, llmRequest, llmResponse, modelResponseEvent) {
1032
1052
  var _a2;
@@ -1144,6 +1164,12 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1144
1164
  llmRequest,
1145
1165
  modelResponseEvent
1146
1166
  )) {
1167
+ (0, import_tracing.traceCallLlm)({
1168
+ invocationContext,
1169
+ eventId: modelResponseEvent.id,
1170
+ llmRequest,
1171
+ llmResponse
1172
+ });
1147
1173
  const alteredLlmResponse = await this.handleAfterModelCallback(
1148
1174
  invocationContext,
1149
1175
  llmResponse,
@@ -68,7 +68,8 @@ class LoopAgent extends (_b = import_base_agent.BaseAgent, _a = LOOP_AGENT_SIGNA
68
68
  }
69
69
  return;
70
70
  }
71
- async *runLiveImpl(context) {
71
+ // eslint-disable-next-line require-yield
72
+ async *runLiveImpl(_context) {
72
73
  throw new Error("This is not supported yet for LoopAgent.");
73
74
  }
74
75
  }
@@ -50,15 +50,14 @@ class ParallelAgent extends (_b = import_base_agent.BaseAgent, _a = PARALLEL_AGE
50
50
  }
51
51
  async *runAsyncImpl(context) {
52
52
  const agentRuns = this.subAgents.map(
53
- (subAgent) => subAgent.runAsync(
54
- createBranchCtxForSubAgent(this, subAgent, context)
55
- )
53
+ (subAgent) => subAgent.runAsync(createBranchCtxForSubAgent(this, subAgent, context))
56
54
  );
57
55
  for await (const event of mergeAgentRuns(agentRuns)) {
58
56
  yield event;
59
57
  }
60
58
  }
61
- async *runLiveImpl(context) {
59
+ // eslint-disable-next-line require-yield
60
+ async *runLiveImpl(_context) {
62
61
  throw new Error("This is not supported yet for ParallelAgent.");
63
62
  }
64
63
  }
@@ -41,10 +41,12 @@ class GcsArtifactService {
41
41
  async saveArtifact(request) {
42
42
  const versions = await this.listVersions(request);
43
43
  const version = versions.length > 0 ? Math.max(...versions) + 1 : 0;
44
- const file = this.bucket.file(getFileName({
45
- ...request,
46
- version
47
- }));
44
+ const file = this.bucket.file(
45
+ getFileName({
46
+ ...request,
47
+ version
48
+ })
49
+ );
48
50
  if (request.artifact.inlineData) {
49
51
  await file.save(JSON.stringify(request.artifact.inlineData.data), {
50
52
  contentType: request.artifact.inlineData.mimeType
@@ -68,11 +70,16 @@ class GcsArtifactService {
68
70
  }
69
71
  version = Math.max(...versions);
70
72
  }
71
- const file = this.bucket.file(getFileName({
72
- ...request,
73
- version
74
- }));
75
- const [[metadata], [rawDataBuffer]] = await Promise.all([file.getMetadata(), file.download()]);
73
+ const file = this.bucket.file(
74
+ getFileName({
75
+ ...request,
76
+ version
77
+ })
78
+ );
79
+ const [[metadata], [rawDataBuffer]] = await Promise.all([
80
+ file.getMetadata(),
81
+ file.download()
82
+ ]);
76
83
  if (metadata.contentType === "text/plain") {
77
84
  return (0, import_genai.createPartFromText)(rawDataBuffer.toString("utf-8"));
78
85
  }
@@ -85,10 +92,7 @@ class GcsArtifactService {
85
92
  const fileNames = [];
86
93
  const sessionPrefix = `${request.appName}/${request.userId}/${request.sessionId}/`;
87
94
  const usernamePrefix = `${request.appName}/${request.userId}/user/`;
88
- const [
89
- [sessionFiles],
90
- [userSessionFiles]
91
- ] = await Promise.all([
95
+ const [[sessionFiles], [userSessionFiles]] = await Promise.all([
92
96
  this.bucket.getFiles({ prefix: sessionPrefix }),
93
97
  this.bucket.getFiles({ prefix: usernamePrefix })
94
98
  ]);
@@ -102,13 +106,17 @@ class GcsArtifactService {
102
106
  }
103
107
  async deleteArtifact(request) {
104
108
  const versions = await this.listVersions(request);
105
- await Promise.all(versions.map((version) => {
106
- const file = this.bucket.file(getFileName({
107
- ...request,
108
- version
109
- }));
110
- return file.delete();
111
- }));
109
+ await Promise.all(
110
+ versions.map((version) => {
111
+ const file = this.bucket.file(
112
+ getFileName({
113
+ ...request,
114
+ version
115
+ })
116
+ );
117
+ return file.delete();
118
+ })
119
+ );
112
120
  return;
113
121
  }
114
122
  async listVersions(request) {