@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
@@ -4,8 +4,16 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { cloneDeep } from "lodash-es";
7
- import { createEvent, getFunctionCalls, getFunctionResponses } from "../events/event.js";
8
- import { removeClientFunctionCallId, REQUEST_CONFIRMATION_FUNCTION_CALL_NAME, REQUEST_EUC_FUNCTION_CALL_NAME } from "./functions.js";
7
+ import {
8
+ createEvent,
9
+ getFunctionCalls,
10
+ getFunctionResponses
11
+ } from "../events/event.js";
12
+ import {
13
+ removeClientFunctionCallId,
14
+ REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
15
+ REQUEST_EUC_FUNCTION_CALL_NAME
16
+ } from "./functions.js";
9
17
  function getContents(events, agentName, currentBranch) {
10
18
  var _a, _b, _c;
11
19
  const filteredEvents = [];
@@ -79,9 +87,11 @@ function convertForeignEvent(event) {
79
87
  }
80
88
  const content = {
81
89
  role: "user",
82
- parts: [{
83
- text: "For context:"
84
- }]
90
+ parts: [
91
+ {
92
+ text: "For context:"
93
+ }
94
+ ]
85
95
  };
86
96
  for (const part of event.content.parts) {
87
97
  if (part.text && !part.thought) {
@@ -183,10 +193,14 @@ function rearrangeEventsForLatestFunctionResponse(events) {
183
193
  const functionCallIds = new Set(
184
194
  functionCalls.map((fc) => fc.id).filter((id) => !!id)
185
195
  );
186
- const isSubset = Array.from(functionResponsesIds).every((id) => functionCallIds.has(id));
196
+ const isSubset = Array.from(functionResponsesIds).every(
197
+ (id) => functionCallIds.has(id)
198
+ );
187
199
  if (!isSubset) {
188
200
  throw new Error(
189
- "Last response event should only contain the responses for the function calls in the same function call event. Function" + " call ids found : ".concat(Array.from(functionCallIds).join(", "), ", function response") + " ids provided: ".concat(Array.from(functionResponsesIds).join(", "))
201
+ "Last response event should only contain the responses for the function calls in the same function call event. Function" + " call ids found : ".concat(Array.from(functionCallIds).join(
202
+ ", "
203
+ ), ", function response") + " ids provided: ".concat(Array.from(functionResponsesIds).join(", "))
190
204
  );
191
205
  }
192
206
  functionResponsesIds = functionCallIds;
@@ -254,7 +268,9 @@ function rearrangeEventsForAsyncFunctionResponsesInHistory(events) {
254
268
  const [responseIndex] = [...functionResponseEventsIndices];
255
269
  resultEvents.push(events[responseIndex]);
256
270
  } else {
257
- const indicesArray = Array.from(functionResponseEventsIndices).sort((a, b) => a - b);
271
+ const indicesArray = Array.from(functionResponseEventsIndices).sort(
272
+ (a, b) => a - b
273
+ );
258
274
  const eventsToMerge = indicesArray.map((index) => events[index]);
259
275
  resultEvents.push(mergeFunctionResponseEvents(eventsToMerge));
260
276
  }
@@ -270,7 +286,7 @@ function safeStringify(obj) {
270
286
  }
271
287
  try {
272
288
  return JSON.stringify(obj);
273
- } catch (e) {
289
+ } catch (_e) {
274
290
  return String(obj);
275
291
  }
276
292
  }
@@ -10,6 +10,11 @@ import { mergeEventActions } from "../events/event_actions.js";
10
10
  import { ToolContext } from "../tools/tool_context.js";
11
11
  import { randomUUID } from "../utils/env_aware_utils.js";
12
12
  import { logger } from "../utils/logger.js";
13
+ import {
14
+ traceMergedToolCalls,
15
+ tracer,
16
+ traceToolCall
17
+ } from "../telemetry/tracing.js";
13
18
  const AF_FUNCTION_CALL_ID_PREFIX = "adk-";
14
19
  const REQUEST_EUC_FUNCTION_CALL_NAME = "adk_request_credential";
15
20
  const REQUEST_CONFIRMATION_FUNCTION_CALL_NAME = "adk_request_confirmation";
@@ -127,8 +132,51 @@ function generateRequestConfirmationEvent({
127
132
  });
128
133
  }
129
134
  async function callToolAsync(tool, args, toolContext) {
130
- logger.debug("callToolAsync ".concat(tool.name));
131
- return await tool.runAsync({ args, toolContext });
135
+ return tracer.startActiveSpan("execute_tool ".concat(tool.name), async (span) => {
136
+ try {
137
+ logger.debug("callToolAsync ".concat(tool.name));
138
+ const result = await tool.runAsync({ args, toolContext });
139
+ traceToolCall({
140
+ tool,
141
+ args,
142
+ functionResponseEvent: buildResponseEvent(
143
+ tool,
144
+ result,
145
+ toolContext,
146
+ toolContext.invocationContext
147
+ )
148
+ });
149
+ return result;
150
+ } finally {
151
+ span.end();
152
+ }
153
+ });
154
+ }
155
+ function buildResponseEvent(tool, functionResult, toolContext, invocationContext) {
156
+ let responseResult;
157
+ if (typeof functionResult !== "object" || functionResult == null) {
158
+ responseResult = { result: functionResult };
159
+ } else {
160
+ responseResult = functionResult;
161
+ }
162
+ const partFunctionResponse = {
163
+ functionResponse: {
164
+ name: tool.name,
165
+ response: responseResult,
166
+ id: toolContext.functionCallId
167
+ }
168
+ };
169
+ const content = {
170
+ role: "user",
171
+ parts: [partFunctionResponse]
172
+ };
173
+ return createEvent({
174
+ invocationId: invocationContext.invocationId,
175
+ author: invocationContext.agent.name,
176
+ content,
177
+ actions: toolContext.actions,
178
+ branch: invocationContext.branch
179
+ });
132
180
  }
133
181
  async function handleFunctionCallsAsync({
134
182
  invocationContext,
@@ -169,14 +217,12 @@ async function handleFunctionCallList({
169
217
  if (toolConfirmationDict && functionCall.id) {
170
218
  toolConfirmation = toolConfirmationDict[functionCall.id];
171
219
  }
172
- const { tool, toolContext } = getToolAndContext(
173
- {
174
- invocationContext,
175
- functionCall,
176
- toolsDict,
177
- toolConfirmation
178
- }
179
- );
220
+ const { tool, toolContext } = getToolAndContext({
221
+ invocationContext,
222
+ functionCall,
223
+ toolsDict,
224
+ toolConfirmation
225
+ });
180
226
  logger.debug("execute_tool ".concat(tool.name));
181
227
  const functionArgs = (_a = functionCall.args) != null ? _a : {};
182
228
  let functionResponse = null;
@@ -200,21 +246,15 @@ async function handleFunctionCallList({
200
246
  }
201
247
  if (functionResponse == null) {
202
248
  try {
203
- functionResponse = await callToolAsync(
204
- tool,
205
- functionArgs,
206
- toolContext
207
- );
249
+ functionResponse = await callToolAsync(tool, functionArgs, toolContext);
208
250
  } catch (e) {
209
251
  if (e instanceof Error) {
210
- const onToolErrorResponse = await invocationContext.pluginManager.runOnToolErrorCallback(
211
- {
212
- tool,
213
- toolArgs: functionArgs,
214
- toolContext,
215
- error: e
216
- }
217
- );
252
+ const onToolErrorResponse = await invocationContext.pluginManager.runOnToolErrorCallback({
253
+ tool,
254
+ toolArgs: functionArgs,
255
+ toolContext,
256
+ error: e
257
+ });
218
258
  if (onToolErrorResponse) {
219
259
  functionResponse = onToolErrorResponse;
220
260
  } else {
@@ -278,12 +318,24 @@ async function handleFunctionCallList({
278
318
  if (!functionResponseEvents.length) {
279
319
  return null;
280
320
  }
281
- const mergedEvent = mergeParallelFunctionResponseEvents(functionResponseEvents);
321
+ const mergedEvent = mergeParallelFunctionResponseEvents(
322
+ functionResponseEvents
323
+ );
282
324
  if (functionResponseEvents.length > 1) {
283
- logger.debug("execute_tool (merged)");
284
- logger.debug("traceMergedToolCalls", {
285
- responseEventId: mergedEvent.id,
286
- functionResponseEvent: mergedEvent.id
325
+ tracer.startActiveSpan("execute_tool (merged)", (span) => {
326
+ try {
327
+ logger.debug("execute_tool (merged)");
328
+ logger.debug("traceMergedToolCalls", {
329
+ responseEventId: mergedEvent.id,
330
+ functionResponseEvent: mergedEvent.id
331
+ });
332
+ traceMergedToolCalls({
333
+ responseEventId: mergedEvent.id,
334
+ functionResponseEvent: mergedEvent
335
+ });
336
+ } finally {
337
+ span.end();
338
+ }
287
339
  });
288
340
  }
289
341
  return mergedEvent;
@@ -321,7 +373,9 @@ function mergeParallelFunctionResponseEvents(functionResponseEvents) {
321
373
  }
322
374
  }
323
375
  const baseEvent = functionResponseEvents[0];
324
- const actionsList = functionResponseEvents.map((event) => event.actions || {});
376
+ const actionsList = functionResponseEvents.map(
377
+ (event) => event.actions || {}
378
+ );
325
379
  const mergedActions = mergeEventActions(actionsList);
326
380
  return createEvent({
327
381
  author: baseEvent.author,
@@ -3,6 +3,9 @@ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
3
  var __hasOwnProp = Object.prototype.hasOwnProperty;
4
4
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
5
  var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
6
+ var __typeError = (msg) => {
7
+ throw TypeError(msg);
8
+ };
6
9
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
10
  var __spreadValues = (a, b) => {
8
11
  for (var prop in b || (b = {}))
@@ -30,6 +33,34 @@ var __asyncGenerator = (__this, __arguments, generator) => {
30
33
  }, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
31
34
  return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
32
35
  };
36
+ var __yieldStar = (value) => {
37
+ var obj = value[__knownSymbol("asyncIterator")], isAwait = false, method, it = {};
38
+ if (obj == null) {
39
+ obj = value[__knownSymbol("iterator")]();
40
+ method = (k) => it[k] = (x) => obj[k](x);
41
+ } else {
42
+ obj = obj.call(value);
43
+ method = (k) => it[k] = (v) => {
44
+ if (isAwait) {
45
+ isAwait = false;
46
+ if (k === "throw") throw v;
47
+ return v;
48
+ }
49
+ isAwait = true;
50
+ return {
51
+ done: false,
52
+ value: new __await(new Promise((resolve) => {
53
+ var x = obj[k](v);
54
+ if (!(x instanceof Object)) __typeError("Object expected");
55
+ resolve(x);
56
+ }), 1)
57
+ };
58
+ };
59
+ }
60
+ return it[__knownSymbol("iterator")] = () => it, method("next"), "throw" in obj ? method("throw") : it.throw = (x) => {
61
+ throw x;
62
+ }, "return" in obj && method("return"), it;
63
+ };
33
64
  var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
34
65
  /**
35
66
  * @license
@@ -37,6 +68,7 @@ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")])
37
68
  * SPDX-License-Identifier: Apache-2.0
38
69
  */
39
70
  var _a, _b;
71
+ import { context, trace } from "@opentelemetry/api";
40
72
  import { cloneDeep } from "lodash-es";
41
73
  import { z } from "zod";
42
74
  import {
@@ -71,6 +103,11 @@ import { ToolConfirmation } from "../tools/tool_confirmation.js";
71
103
  import { ToolContext } from "../tools/tool_context.js";
72
104
  import { base64Decode } from "../utils/env_aware_utils.js";
73
105
  import { logger } from "../utils/logger.js";
106
+ import {
107
+ runAsyncGeneratorWithOtelContext,
108
+ traceCallLlm,
109
+ tracer
110
+ } from "../telemetry/tracing.js";
74
111
  import { BaseAgent } from "./base_agent.js";
75
112
  import {
76
113
  BaseLlmRequestProcessor
@@ -93,13 +130,14 @@ import { injectSessionState } from "./instructions.js";
93
130
  import { ReadonlyContext } from "./readonly_context.js";
94
131
  import { StreamingMode } from "./run_config.js";
95
132
  const ADK_AGENT_NAME_LABEL_KEY = "adk_agent_name";
96
- async function convertToolUnionToTools(toolUnion, context) {
133
+ async function convertToolUnionToTools(toolUnion, context2) {
97
134
  if (toolUnion instanceof BaseTool) {
98
135
  return [toolUnion];
99
136
  }
100
- return await toolUnion.getTools(context);
137
+ return await toolUnion.getTools(context2);
101
138
  }
102
139
  class BasicLlmRequestProcessor extends BaseLlmRequestProcessor {
140
+ // eslint-disable-next-line require-yield
103
141
  runAsync(invocationContext, llmRequest) {
104
142
  return __asyncGenerator(this, null, function* () {
105
143
  var _a2;
@@ -126,6 +164,7 @@ class BasicLlmRequestProcessor extends BaseLlmRequestProcessor {
126
164
  }
127
165
  const BASIC_LLM_REQUEST_PROCESSOR = new BasicLlmRequestProcessor();
128
166
  class IdentityLlmRequestProcessor extends BaseLlmRequestProcessor {
167
+ // eslint-disable-next-line require-yield
129
168
  runAsync(invocationContext, llmRequest) {
130
169
  return __asyncGenerator(this, null, function* () {
131
170
  const agent = invocationContext.agent;
@@ -142,6 +181,7 @@ class InstructionsLlmRequestProcessor extends BaseLlmRequestProcessor {
142
181
  /**
143
182
  * Handles instructions and global instructions for LLM flow.
144
183
  */
184
+ // eslint-disable-next-line require-yield
145
185
  runAsync(invocationContext, llmRequest) {
146
186
  return __asyncGenerator(this, null, function* () {
147
187
  const agent = invocationContext.agent;
@@ -180,6 +220,7 @@ class InstructionsLlmRequestProcessor extends BaseLlmRequestProcessor {
180
220
  }
181
221
  const INSTRUCTIONS_LLM_REQUEST_PROCESSOR = new InstructionsLlmRequestProcessor();
182
222
  class ContentRequestProcessor {
223
+ // eslint-disable-next-line require-yield
183
224
  runAsync(invocationContext, llmRequest) {
184
225
  return __asyncGenerator(this, null, function* () {
185
226
  const agent = invocationContext.agent;
@@ -223,6 +264,7 @@ class AgentTransferLlmRequestProcessor extends BaseLlmRequestProcessor {
223
264
  }
224
265
  });
225
266
  }
267
+ // eslint-disable-next-line require-yield
226
268
  runAsync(invocationContext, llmRequest) {
227
269
  return __asyncGenerator(this, null, function* () {
228
270
  if (!(invocationContext.agent instanceof LlmAgent)) {
@@ -274,7 +316,7 @@ class AgentTransferLlmRequestProcessor extends BaseLlmRequestProcessor {
274
316
  const AGENT_TRANSFER_LLM_REQUEST_PROCESSOR = new AgentTransferLlmRequestProcessor();
275
317
  class RequestConfirmationLlmRequestProcessor extends BaseLlmRequestProcessor {
276
318
  /** Handles tool confirmation information to build the LLM request. */
277
- runAsync(invocationContext, llmRequest) {
319
+ runAsync(invocationContext) {
278
320
  return __asyncGenerator(this, null, function* () {
279
321
  const agent = invocationContext.agent;
280
322
  if (!isLlmAgent(agent)) {
@@ -422,7 +464,7 @@ class CodeExecutionRequestProcessor extends BaseLlmRequestProcessor {
422
464
  }
423
465
  for (const content of llmRequest.contents) {
424
466
  const delimeters = invocationContext.agent.codeExecutor.codeBlockDelimiters.length ? invocationContext.agent.codeExecutor.codeBlockDelimiters[0] : ["", ""];
425
- const codeExecutionParts = convertCodeExecutionParts(
467
+ convertCodeExecutionParts(
426
468
  content,
427
469
  delimeters,
428
470
  invocationContext.agent.codeExecutor.executionResultDelimiters
@@ -613,7 +655,7 @@ function runPostProcessor(invocationContext, llmResponse) {
613
655
  codeExecutorContext,
614
656
  codeExecutionResult
615
657
  ));
616
- llmResponse.content = null;
658
+ llmResponse.content = void 0;
617
659
  });
618
660
  }
619
661
  function extractAndReplaceInlineFiles(codeExecutorContext, llmRequest) {
@@ -817,12 +859,12 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
817
859
  * @param context The context to retrieve the session state.
818
860
  * @returns The resolved instruction field.
819
861
  */
820
- async canonicalInstruction(context) {
862
+ async canonicalInstruction(context2) {
821
863
  if (typeof this.instruction === "string") {
822
864
  return { instruction: this.instruction, requireStateInjection: true };
823
865
  }
824
866
  return {
825
- instruction: await this.instruction(context),
867
+ instruction: await this.instruction(context2),
826
868
  requireStateInjection: false
827
869
  };
828
870
  }
@@ -833,12 +875,15 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
833
875
  * @param context The context to retrieve the session state.
834
876
  * @returns The resolved globalInstruction field.
835
877
  */
836
- async canonicalGlobalInstruction(context) {
878
+ async canonicalGlobalInstruction(context2) {
837
879
  if (typeof this.globalInstruction === "string") {
838
- return { instruction: this.globalInstruction, requireStateInjection: true };
880
+ return {
881
+ instruction: this.globalInstruction,
882
+ requireStateInjection: true
883
+ };
839
884
  }
840
885
  return {
841
- instruction: await this.globalInstruction(context),
886
+ instruction: await this.globalInstruction(context2),
842
887
  requireStateInjection: false
843
888
  };
844
889
  }
@@ -847,10 +892,10 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
847
892
  *
848
893
  * This method is only for use by Agent Development Kit.
849
894
  */
850
- async canonicalTools(context) {
895
+ async canonicalTools(context2) {
851
896
  const resolvedTools = [];
852
897
  for (const toolUnion of this.tools) {
853
- const tools = await convertToolUnionToTools(toolUnion, context);
898
+ const tools = await convertToolUnionToTools(toolUnion, context2);
854
899
  resolvedTools.push(...tools);
855
900
  }
856
901
  return resolvedTools;
@@ -954,12 +999,12 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
954
999
  }
955
1000
  event.actions.stateDelta[this.outputKey] = result;
956
1001
  }
957
- runAsyncImpl(context) {
1002
+ runAsyncImpl(context2) {
958
1003
  return __asyncGenerator(this, null, function* () {
959
1004
  while (true) {
960
1005
  let lastEvent = void 0;
961
1006
  try {
962
- for (var iter = __forAwait(this.runOneStepAsync(context)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
1007
+ for (var iter = __forAwait(this.runOneStepAsync(context2)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
963
1008
  const event = temp.value;
964
1009
  lastEvent = event;
965
1010
  this.maybeSaveOutputToState(event);
@@ -985,10 +1030,10 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
985
1030
  }
986
1031
  });
987
1032
  }
988
- runLiveImpl(context) {
1033
+ runLiveImpl(context2) {
989
1034
  return __asyncGenerator(this, null, function* () {
990
1035
  try {
991
- for (var iter = __forAwait(this.runLiveFlow(context)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
1036
+ for (var iter = __forAwait(this.runLiveFlow(context2)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
992
1037
  const event = temp.value;
993
1038
  this.maybeSaveOutputToState(event);
994
1039
  yield event;
@@ -1003,7 +1048,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1003
1048
  throw error[0];
1004
1049
  }
1005
1050
  }
1006
- if (context.endInvocation) {
1051
+ if (context2.endInvocation) {
1007
1052
  return;
1008
1053
  }
1009
1054
  });
@@ -1011,7 +1056,8 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1011
1056
  // --------------------------------------------------------------------------
1012
1057
  // #START LlmFlow Logic
1013
1058
  // --------------------------------------------------------------------------
1014
- runLiveFlow(invocationContext) {
1059
+ // eslint-disable-next-line require-yield
1060
+ runLiveFlow(_invocationContext) {
1015
1061
  return __asyncGenerator(this, null, function* () {
1016
1062
  yield new __await(Promise.resolve());
1017
1063
  throw new Error("LlmAgent.runLiveFlow not implemented");
@@ -1062,46 +1108,57 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1062
1108
  author: this.name,
1063
1109
  branch: invocationContext.branch
1064
1110
  });
1065
- try {
1066
- for (var iter3 = __forAwait(this.callLlmAsync(
1067
- invocationContext,
1068
- llmRequest,
1069
- modelResponseEvent
1070
- )), more3, temp3, error3; more3 = !(temp3 = yield new __await(iter3.next())).done; more3 = false) {
1071
- const llmResponse = temp3.value;
1072
- try {
1073
- for (var iter2 = __forAwait(this.postprocess(
1074
- invocationContext,
1075
- llmRequest,
1076
- llmResponse,
1077
- modelResponseEvent
1078
- )), more2, temp2, error2; more2 = !(temp2 = yield new __await(iter2.next())).done; more2 = false) {
1079
- const event = temp2.value;
1080
- modelResponseEvent.id = createNewEventId();
1081
- modelResponseEvent.timestamp = (/* @__PURE__ */ new Date()).getTime();
1082
- yield event;
1083
- }
1084
- } catch (temp2) {
1085
- error2 = [temp2];
1086
- } finally {
1111
+ const span = tracer.startSpan("call_llm");
1112
+ const ctx = trace.setSpan(context.active(), span);
1113
+ yield* __yieldStar(runAsyncGeneratorWithOtelContext(
1114
+ ctx,
1115
+ this,
1116
+ function() {
1117
+ return __asyncGenerator(this, null, function* () {
1087
1118
  try {
1088
- more2 && (temp2 = iter2.return) && (yield new __await(temp2.call(iter2)));
1119
+ for (var iter3 = __forAwait(this.callLlmAsync(
1120
+ invocationContext,
1121
+ llmRequest,
1122
+ modelResponseEvent
1123
+ )), more3, temp3, error3; more3 = !(temp3 = yield new __await(iter3.next())).done; more3 = false) {
1124
+ const llmResponse = temp3.value;
1125
+ try {
1126
+ for (var iter2 = __forAwait(this.postprocess(
1127
+ invocationContext,
1128
+ llmRequest,
1129
+ llmResponse,
1130
+ modelResponseEvent
1131
+ )), more2, temp2, error2; more2 = !(temp2 = yield new __await(iter2.next())).done; more2 = false) {
1132
+ const event = temp2.value;
1133
+ modelResponseEvent.id = createNewEventId();
1134
+ modelResponseEvent.timestamp = (/* @__PURE__ */ new Date()).getTime();
1135
+ yield event;
1136
+ }
1137
+ } catch (temp2) {
1138
+ error2 = [temp2];
1139
+ } finally {
1140
+ try {
1141
+ more2 && (temp2 = iter2.return) && (yield new __await(temp2.call(iter2)));
1142
+ } finally {
1143
+ if (error2)
1144
+ throw error2[0];
1145
+ }
1146
+ }
1147
+ }
1148
+ } catch (temp3) {
1149
+ error3 = [temp3];
1089
1150
  } finally {
1090
- if (error2)
1091
- throw error2[0];
1151
+ try {
1152
+ more3 && (temp3 = iter3.return) && (yield new __await(temp3.call(iter3)));
1153
+ } finally {
1154
+ if (error3)
1155
+ throw error3[0];
1156
+ }
1092
1157
  }
1093
- }
1158
+ });
1094
1159
  }
1095
- } catch (temp3) {
1096
- error3 = [temp3];
1097
- } finally {
1098
- try {
1099
- more3 && (temp3 = iter3.return) && (yield new __await(temp3.call(iter3)));
1100
- } finally {
1101
- if (error3)
1102
- throw error3[0];
1103
- }
1104
- }
1160
+ ));
1161
+ span.end();
1105
1162
  });
1106
1163
  }
1107
1164
  postprocess(invocationContext, llmRequest, llmResponse, modelResponseEvent) {
@@ -1246,6 +1303,12 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1246
1303
  modelResponseEvent
1247
1304
  )), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
1248
1305
  const llmResponse = temp.value;
1306
+ traceCallLlm({
1307
+ invocationContext,
1308
+ eventId: modelResponseEvent.id,
1309
+ llmRequest,
1310
+ llmResponse
1311
+ });
1249
1312
  const alteredLlmResponse = yield new __await(this.handleAfterModelCallback(
1250
1313
  invocationContext,
1251
1314
  llmResponse,
@@ -69,7 +69,8 @@ class LoopAgent extends (_b = BaseAgent, _a = LOOP_AGENT_SIGNATURE_SYMBOL, _b) {
69
69
  return;
70
70
  });
71
71
  }
72
- runLiveImpl(context) {
72
+ // eslint-disable-next-line require-yield
73
+ runLiveImpl(_context) {
73
74
  return __asyncGenerator(this, null, function* () {
74
75
  throw new Error("This is not supported yet for LoopAgent.");
75
76
  });
@@ -38,9 +38,7 @@ class ParallelAgent extends (_b = BaseAgent, _a = PARALLEL_AGENT_SIGNATURE_SYMBO
38
38
  runAsyncImpl(context) {
39
39
  return __asyncGenerator(this, null, function* () {
40
40
  const agentRuns = this.subAgents.map(
41
- (subAgent) => subAgent.runAsync(
42
- createBranchCtxForSubAgent(this, subAgent, context)
43
- )
41
+ (subAgent) => subAgent.runAsync(createBranchCtxForSubAgent(this, subAgent, context))
44
42
  );
45
43
  try {
46
44
  for (var iter = __forAwait(mergeAgentRuns(agentRuns)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
@@ -59,7 +57,8 @@ class ParallelAgent extends (_b = BaseAgent, _a = PARALLEL_AGENT_SIGNATURE_SYMBO
59
57
  }
60
58
  });
61
59
  }
62
- runLiveImpl(context) {
60
+ // eslint-disable-next-line require-yield
61
+ runLiveImpl(_context) {
63
62
  return __asyncGenerator(this, null, function* () {
64
63
  throw new Error("This is not supported yet for ParallelAgent.");
65
64
  });
@@ -31,9 +31,11 @@ class GcsArtifactService {
31
31
  async saveArtifact(request) {
32
32
  const versions = await this.listVersions(request);
33
33
  const version = versions.length > 0 ? Math.max(...versions) + 1 : 0;
34
- const file = this.bucket.file(getFileName(__spreadProps(__spreadValues({}, request), {
35
- version
36
- })));
34
+ const file = this.bucket.file(
35
+ getFileName(__spreadProps(__spreadValues({}, request), {
36
+ version
37
+ }))
38
+ );
37
39
  if (request.artifact.inlineData) {
38
40
  await file.save(JSON.stringify(request.artifact.inlineData.data), {
39
41
  contentType: request.artifact.inlineData.mimeType
@@ -57,10 +59,15 @@ class GcsArtifactService {
57
59
  }
58
60
  version = Math.max(...versions);
59
61
  }
60
- const file = this.bucket.file(getFileName(__spreadProps(__spreadValues({}, request), {
61
- version
62
- })));
63
- const [[metadata], [rawDataBuffer]] = await Promise.all([file.getMetadata(), file.download()]);
62
+ const file = this.bucket.file(
63
+ getFileName(__spreadProps(__spreadValues({}, request), {
64
+ version
65
+ }))
66
+ );
67
+ const [[metadata], [rawDataBuffer]] = await Promise.all([
68
+ file.getMetadata(),
69
+ file.download()
70
+ ]);
64
71
  if (metadata.contentType === "text/plain") {
65
72
  return createPartFromText(rawDataBuffer.toString("utf-8"));
66
73
  }
@@ -73,10 +80,7 @@ class GcsArtifactService {
73
80
  const fileNames = [];
74
81
  const sessionPrefix = "".concat(request.appName, "/").concat(request.userId, "/").concat(request.sessionId, "/");
75
82
  const usernamePrefix = "".concat(request.appName, "/").concat(request.userId, "/user/");
76
- const [
77
- [sessionFiles],
78
- [userSessionFiles]
79
- ] = await Promise.all([
83
+ const [[sessionFiles], [userSessionFiles]] = await Promise.all([
80
84
  this.bucket.getFiles({ prefix: sessionPrefix }),
81
85
  this.bucket.getFiles({ prefix: usernamePrefix })
82
86
  ]);
@@ -90,12 +94,16 @@ class GcsArtifactService {
90
94
  }
91
95
  async deleteArtifact(request) {
92
96
  const versions = await this.listVersions(request);
93
- await Promise.all(versions.map((version) => {
94
- const file = this.bucket.file(getFileName(__spreadProps(__spreadValues({}, request), {
95
- version
96
- })));
97
- return file.delete();
98
- }));
97
+ await Promise.all(
98
+ versions.map((version) => {
99
+ const file = this.bucket.file(
100
+ getFileName(__spreadProps(__spreadValues({}, request), {
101
+ version
102
+ }))
103
+ );
104
+ return file.delete();
105
+ })
106
+ );
99
107
  return;
100
108
  }
101
109
  async listVersions(request) {