@google/adk 0.3.0 → 0.5.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 (265) hide show
  1. package/dist/cjs/a2a/a2a_event.js +290 -0
  2. package/dist/cjs/a2a/event_converter_utils.js +201 -0
  3. package/dist/cjs/a2a/executor_context.js +53 -0
  4. package/dist/cjs/a2a/metadata_converter_utils.js +125 -0
  5. package/dist/cjs/a2a/part_converter_utils.js +212 -0
  6. package/dist/cjs/agents/active_streaming_tool.js +1 -1
  7. package/dist/cjs/agents/base_agent.js +6 -6
  8. package/dist/cjs/agents/content_processor_utils.js +1 -1
  9. package/dist/cjs/{tools/tool_context.js → agents/context.js} +71 -16
  10. package/dist/cjs/agents/functions.js +4 -3
  11. package/dist/cjs/agents/instructions.js +1 -1
  12. package/dist/cjs/agents/invocation_context.js +1 -1
  13. package/dist/cjs/agents/live_request_queue.js +1 -1
  14. package/dist/cjs/agents/llm_agent.js +76 -711
  15. package/dist/cjs/agents/loop_agent.js +1 -1
  16. package/dist/cjs/agents/parallel_agent.js +1 -1
  17. package/dist/cjs/agents/processors/agent_transfer_llm_request_processor.js +132 -0
  18. package/dist/cjs/agents/{base_llm_processor.js → processors/base_llm_processor.js} +1 -1
  19. package/dist/cjs/agents/processors/basic_llm_request_processor.js +68 -0
  20. package/dist/cjs/agents/processors/code_execution_request_processor.js +389 -0
  21. package/dist/cjs/agents/processors/content_request_processor.js +66 -0
  22. package/dist/cjs/agents/processors/identity_llm_request_processor.js +54 -0
  23. package/dist/cjs/agents/processors/instructions_llm_request_processor.js +85 -0
  24. package/dist/cjs/agents/processors/request_confirmation_llm_request_processor.js +165 -0
  25. package/dist/cjs/agents/readonly_context.js +13 -1
  26. package/dist/cjs/agents/run_config.js +2 -1
  27. package/dist/cjs/agents/sequential_agent.js +1 -1
  28. package/dist/cjs/agents/transcription_entry.js +1 -1
  29. package/dist/cjs/artifacts/base_artifact_service.js +1 -1
  30. package/dist/cjs/artifacts/file_artifact_service.js +491 -0
  31. package/dist/cjs/artifacts/gcs_artifact_service.js +127 -48
  32. package/dist/cjs/artifacts/in_memory_artifact_service.js +54 -6
  33. package/dist/cjs/artifacts/registry.js +55 -0
  34. package/dist/cjs/auth/auth_credential.js +1 -1
  35. package/dist/cjs/auth/auth_handler.js +1 -1
  36. package/dist/cjs/auth/auth_schemes.js +1 -1
  37. package/dist/cjs/auth/auth_tool.js +1 -1
  38. package/dist/cjs/auth/credential_service/base_credential_service.js +1 -1
  39. package/dist/cjs/auth/credential_service/in_memory_credential_service.js +1 -1
  40. package/dist/cjs/auth/exchanger/base_credential_exchanger.js +1 -1
  41. package/dist/cjs/auth/exchanger/credential_exchanger_registry.js +1 -1
  42. package/dist/cjs/code_executors/base_code_executor.js +1 -1
  43. package/dist/cjs/code_executors/built_in_code_executor.js +1 -1
  44. package/dist/cjs/code_executors/code_execution_utils.js +1 -1
  45. package/dist/cjs/code_executors/code_executor_context.js +1 -1
  46. package/dist/cjs/common.js +25 -8
  47. package/dist/cjs/events/event.js +33 -4
  48. package/dist/cjs/events/event_actions.js +2 -2
  49. package/dist/cjs/events/structured_events.js +105 -0
  50. package/dist/cjs/examples/base_example_provider.js +1 -1
  51. package/dist/cjs/examples/example.js +1 -1
  52. package/dist/cjs/examples/example_util.js +1 -1
  53. package/dist/cjs/index.js +24 -17
  54. package/dist/cjs/index.js.map +4 -4
  55. package/dist/cjs/index_web.js +1 -1
  56. package/dist/cjs/memory/base_memory_service.js +1 -1
  57. package/dist/cjs/memory/in_memory_memory_service.js +1 -1
  58. package/dist/cjs/memory/memory_entry.js +1 -1
  59. package/dist/cjs/models/apigee_llm.js +182 -0
  60. package/dist/cjs/models/base_llm.js +1 -1
  61. package/dist/cjs/models/base_llm_connection.js +1 -1
  62. package/dist/cjs/models/gemini_llm_connection.js +1 -1
  63. package/dist/cjs/models/google_llm.js +70 -51
  64. package/dist/cjs/models/llm_request.js +1 -1
  65. package/dist/cjs/models/llm_response.js +3 -1
  66. package/dist/cjs/models/registry.js +3 -1
  67. package/dist/cjs/plugins/base_plugin.js +2 -2
  68. package/dist/cjs/plugins/logging_plugin.js +1 -1
  69. package/dist/cjs/plugins/plugin_manager.js +1 -1
  70. package/dist/cjs/plugins/security_plugin.js +1 -1
  71. package/dist/cjs/runner/in_memory_runner.js +1 -1
  72. package/dist/cjs/runner/runner.js +33 -2
  73. package/dist/cjs/sessions/base_session_service.js +53 -3
  74. package/dist/cjs/sessions/database_session_service.js +367 -0
  75. package/dist/cjs/sessions/db/operations.js +126 -0
  76. package/dist/cjs/sessions/db/schema.js +204 -0
  77. package/dist/cjs/sessions/in_memory_session_service.js +24 -22
  78. package/dist/cjs/sessions/registry.js +49 -0
  79. package/dist/cjs/sessions/session.js +1 -1
  80. package/dist/cjs/sessions/state.js +1 -1
  81. package/dist/cjs/telemetry/google_cloud.js +1 -1
  82. package/dist/cjs/telemetry/setup.js +1 -1
  83. package/dist/cjs/telemetry/tracing.js +1 -1
  84. package/dist/cjs/tools/agent_tool.js +1 -1
  85. package/dist/cjs/tools/base_tool.js +4 -1
  86. package/dist/cjs/tools/base_toolset.js +14 -4
  87. package/dist/cjs/tools/exit_loop_tool.js +63 -0
  88. package/dist/cjs/tools/forwarding_artifact_service.js +17 -1
  89. package/dist/cjs/tools/function_tool.js +1 -1
  90. package/dist/cjs/tools/google_search_tool.js +1 -1
  91. package/dist/cjs/tools/long_running_tool.js +1 -1
  92. package/dist/cjs/tools/mcp/mcp_session_manager.js +1 -1
  93. package/dist/cjs/tools/mcp/mcp_tool.js +1 -1
  94. package/dist/cjs/tools/mcp/mcp_toolset.js +10 -6
  95. package/dist/cjs/tools/tool_confirmation.js +1 -1
  96. package/dist/cjs/utils/client_labels.js +1 -1
  97. package/dist/cjs/utils/env_aware_utils.js +10 -1
  98. package/dist/cjs/utils/gemini_schema_util.js +1 -1
  99. package/dist/cjs/utils/logger.js +62 -55
  100. package/dist/cjs/utils/model_name.js +1 -1
  101. package/dist/cjs/utils/object_notation_utils.js +78 -0
  102. package/dist/cjs/utils/simple_zod_to_json.js +1 -1
  103. package/dist/cjs/utils/variant_utils.js +3 -9
  104. package/dist/cjs/version.js +2 -2
  105. package/dist/esm/a2a/a2a_event.js +243 -0
  106. package/dist/esm/a2a/event_converter_utils.js +187 -0
  107. package/dist/esm/a2a/executor_context.js +23 -0
  108. package/dist/esm/a2a/metadata_converter_utils.js +90 -0
  109. package/dist/esm/a2a/part_converter_utils.js +175 -0
  110. package/dist/esm/agents/base_agent.js +5 -5
  111. package/dist/esm/{tools/tool_context.js → agents/context.js} +66 -11
  112. package/dist/esm/agents/functions.js +3 -2
  113. package/dist/esm/agents/llm_agent.js +69 -720
  114. package/dist/esm/agents/processors/agent_transfer_llm_request_processor.js +101 -0
  115. package/dist/esm/agents/processors/basic_llm_request_processor.js +37 -0
  116. package/dist/esm/agents/processors/code_execution_request_processor.js +363 -0
  117. package/dist/esm/agents/processors/content_request_processor.js +38 -0
  118. package/dist/esm/agents/processors/identity_llm_request_processor.js +23 -0
  119. package/dist/esm/agents/processors/instructions_llm_request_processor.js +54 -0
  120. package/dist/esm/agents/processors/request_confirmation_llm_request_processor.js +140 -0
  121. package/dist/esm/agents/readonly_context.js +12 -0
  122. package/dist/esm/agents/run_config.js +1 -0
  123. package/dist/esm/artifacts/file_artifact_service.js +451 -0
  124. package/dist/esm/artifacts/gcs_artifact_service.js +126 -47
  125. package/dist/esm/artifacts/in_memory_artifact_service.js +51 -4
  126. package/dist/esm/artifacts/registry.js +28 -0
  127. package/dist/esm/common.js +20 -10
  128. package/dist/esm/events/event.js +29 -2
  129. package/dist/esm/events/event_actions.js +1 -1
  130. package/dist/esm/events/structured_events.js +74 -0
  131. package/dist/esm/index.js +24 -17
  132. package/dist/esm/index.js.map +4 -4
  133. package/dist/esm/models/apigee_llm.js +152 -0
  134. package/dist/esm/models/google_llm.js +67 -49
  135. package/dist/esm/models/llm_response.js +2 -0
  136. package/dist/esm/models/registry.js +2 -0
  137. package/dist/esm/plugins/base_plugin.js +1 -1
  138. package/dist/esm/runner/runner.js +32 -1
  139. package/dist/esm/sessions/base_session_service.js +49 -1
  140. package/dist/esm/sessions/database_session_service.js +353 -0
  141. package/dist/esm/sessions/db/operations.js +111 -0
  142. package/dist/esm/sessions/db/schema.js +172 -0
  143. package/dist/esm/sessions/in_memory_session_service.js +23 -21
  144. package/dist/esm/sessions/registry.js +25 -0
  145. package/dist/esm/tools/base_tool.js +3 -0
  146. package/dist/esm/tools/base_toolset.js +11 -2
  147. package/dist/esm/tools/exit_loop_tool.js +32 -0
  148. package/dist/esm/tools/forwarding_artifact_service.js +16 -0
  149. package/dist/esm/tools/mcp/mcp_toolset.js +9 -5
  150. package/dist/esm/utils/env_aware_utils.js +8 -0
  151. package/dist/esm/utils/logger.js +51 -54
  152. package/dist/esm/utils/object_notation_utils.js +47 -0
  153. package/dist/esm/utils/variant_utils.js +1 -7
  154. package/dist/esm/version.js +1 -1
  155. package/dist/types/a2a/a2a_event.d.ts +122 -0
  156. package/dist/types/a2a/event_converter_utils.d.ts +20 -0
  157. package/dist/types/a2a/executor_context.d.ts +33 -0
  158. package/dist/types/a2a/metadata_converter_utils.d.ts +62 -0
  159. package/dist/types/a2a/part_converter_utils.d.ts +48 -0
  160. package/dist/types/agents/base_agent.d.ts +2 -2
  161. package/dist/types/{tools/tool_context.d.ts → agents/context.d.ts} +43 -8
  162. package/dist/types/agents/llm_agent.d.ts +19 -42
  163. package/dist/types/agents/processors/agent_transfer_llm_request_processor.d.ts +18 -0
  164. package/dist/types/agents/{base_llm_processor.d.ts → processors/base_llm_processor.d.ts} +4 -4
  165. package/dist/types/agents/processors/basic_llm_request_processor.d.ts +13 -0
  166. package/dist/types/agents/processors/code_execution_request_processor.d.ts +34 -0
  167. package/dist/types/agents/processors/content_request_processor.d.ts +13 -0
  168. package/dist/types/agents/processors/identity_llm_request_processor.d.ts +13 -0
  169. package/dist/types/agents/processors/instructions_llm_request_processor.d.ts +16 -0
  170. package/dist/types/agents/processors/request_confirmation_llm_request_processor.d.ts +13 -0
  171. package/dist/types/agents/readonly_context.d.ts +8 -0
  172. package/dist/types/agents/run_config.d.ts +6 -0
  173. package/dist/types/artifacts/base_artifact_service.d.ts +31 -0
  174. package/dist/types/artifacts/file_artifact_service.d.ts +43 -0
  175. package/dist/types/artifacts/gcs_artifact_service.d.ts +3 -1
  176. package/dist/types/artifacts/in_memory_artifact_service.d.ts +5 -2
  177. package/dist/types/artifacts/registry.d.ts +7 -0
  178. package/dist/types/auth/credential_service/base_credential_service.d.ts +3 -3
  179. package/dist/types/auth/credential_service/in_memory_credential_service.d.ts +3 -3
  180. package/dist/types/common.d.ts +15 -6
  181. package/dist/types/events/event.d.ts +15 -1
  182. package/dist/types/events/event_actions.d.ts +1 -1
  183. package/dist/types/events/structured_events.d.ts +106 -0
  184. package/dist/types/index.d.ts +5 -1
  185. package/dist/types/models/apigee_llm.d.ts +59 -0
  186. package/dist/types/models/google_llm.d.ts +5 -2
  187. package/dist/types/models/llm_response.d.ts +5 -1
  188. package/dist/types/plugins/base_plugin.d.ts +12 -13
  189. package/dist/types/plugins/logging_plugin.d.ts +9 -10
  190. package/dist/types/plugins/plugin_manager.d.ts +9 -10
  191. package/dist/types/plugins/security_plugin.d.ts +2 -2
  192. package/dist/types/runner/runner.d.ts +15 -0
  193. package/dist/types/sessions/base_session_service.d.ts +20 -0
  194. package/dist/types/sessions/database_session_service.d.ts +32 -0
  195. package/dist/types/sessions/db/operations.d.ts +29 -0
  196. package/dist/types/sessions/db/schema.d.ts +45 -0
  197. package/dist/types/sessions/in_memory_session_service.d.ts +4 -1
  198. package/dist/types/sessions/registry.d.ts +7 -0
  199. package/dist/types/tools/base_tool.d.ts +3 -3
  200. package/dist/types/tools/base_toolset.d.ts +12 -3
  201. package/dist/types/tools/exit_loop_tool.d.ts +24 -0
  202. package/dist/types/tools/forwarding_artifact_service.d.ts +5 -3
  203. package/dist/types/tools/function_tool.d.ts +2 -2
  204. package/dist/types/tools/mcp/mcp_toolset.d.ts +1 -1
  205. package/dist/types/utils/env_aware_utils.d.ts +7 -0
  206. package/dist/types/utils/logger.d.ts +5 -9
  207. package/dist/types/utils/object_notation_utils.d.ts +21 -0
  208. package/dist/types/version.d.ts +1 -1
  209. package/dist/web/a2a/a2a_event.js +243 -0
  210. package/dist/web/a2a/event_converter_utils.js +201 -0
  211. package/dist/web/a2a/executor_context.js +23 -0
  212. package/dist/web/a2a/metadata_converter_utils.js +107 -0
  213. package/dist/web/a2a/part_converter_utils.js +175 -0
  214. package/dist/web/agents/base_agent.js +5 -5
  215. package/dist/web/{tools/tool_context.js → agents/context.js} +66 -11
  216. package/dist/web/agents/functions.js +3 -2
  217. package/dist/web/agents/llm_agent.js +90 -717
  218. package/dist/web/agents/processors/agent_transfer_llm_request_processor.js +100 -0
  219. package/dist/web/agents/processors/basic_llm_request_processor.js +71 -0
  220. package/dist/web/agents/processors/code_execution_request_processor.js +365 -0
  221. package/dist/web/agents/processors/content_request_processor.js +56 -0
  222. package/dist/web/agents/processors/identity_llm_request_processor.js +41 -0
  223. package/dist/web/agents/processors/instructions_llm_request_processor.js +72 -0
  224. package/dist/web/agents/processors/request_confirmation_llm_request_processor.js +158 -0
  225. package/dist/web/agents/readonly_context.js +12 -0
  226. package/dist/web/agents/run_config.js +2 -1
  227. package/dist/web/artifacts/file_artifact_service.js +506 -0
  228. package/dist/web/artifacts/gcs_artifact_service.js +123 -46
  229. package/dist/web/artifacts/in_memory_artifact_service.js +51 -4
  230. package/dist/web/artifacts/registry.js +28 -0
  231. package/dist/web/common.js +20 -10
  232. package/dist/web/events/event.js +29 -2
  233. package/dist/web/events/event_actions.js +1 -1
  234. package/dist/web/events/structured_events.js +74 -0
  235. package/dist/web/index.js +7 -2
  236. package/dist/web/index.js.map +4 -4
  237. package/dist/web/models/apigee_llm.js +219 -0
  238. package/dist/web/models/google_llm.js +67 -46
  239. package/dist/web/models/llm_response.js +2 -0
  240. package/dist/web/models/registry.js +2 -0
  241. package/dist/web/plugins/base_plugin.js +1 -1
  242. package/dist/web/runner/runner.js +34 -1
  243. package/dist/web/sessions/base_session_service.js +49 -1
  244. package/dist/web/sessions/database_session_service.js +371 -0
  245. package/dist/web/sessions/db/operations.js +111 -0
  246. package/dist/web/sessions/db/schema.js +172 -0
  247. package/dist/web/sessions/in_memory_session_service.js +23 -21
  248. package/dist/web/sessions/registry.js +25 -0
  249. package/dist/web/tools/base_tool.js +3 -0
  250. package/dist/web/tools/base_toolset.js +11 -2
  251. package/dist/web/tools/exit_loop_tool.js +32 -0
  252. package/dist/web/tools/forwarding_artifact_service.js +16 -0
  253. package/dist/web/tools/mcp/mcp_toolset.js +27 -5
  254. package/dist/web/utils/env_aware_utils.js +8 -0
  255. package/dist/web/utils/logger.js +51 -54
  256. package/dist/web/utils/object_notation_utils.js +47 -0
  257. package/dist/web/utils/variant_utils.js +1 -7
  258. package/dist/web/version.js +1 -1
  259. package/package.json +13 -3
  260. package/dist/cjs/agents/callback_context.js +0 -101
  261. package/dist/esm/agents/callback_context.js +0 -71
  262. package/dist/types/agents/callback_context.d.ts +0 -42
  263. package/dist/web/agents/callback_context.js +0 -71
  264. /package/dist/esm/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
  265. /package/dist/web/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @license
3
- * Copyright 2025 Google LLC
3
+ * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
@@ -25,37 +25,27 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
25
25
  var llm_agent_exports = {};
26
26
  __export(llm_agent_exports, {
27
27
  LlmAgent: () => LlmAgent,
28
- REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR: () => REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
29
- isLlmAgent: () => isLlmAgent,
30
- responseProcessor: () => responseProcessor
28
+ isLlmAgent: () => isLlmAgent
31
29
  });
32
30
  module.exports = __toCommonJS(llm_agent_exports);
33
31
  var import_api = require("@opentelemetry/api");
34
- var import_lodash_es = require("lodash-es");
35
- var import_zod = require("zod");
36
- var import_base_code_executor = require("../code_executors/base_code_executor.js");
37
- var import_built_in_code_executor = require("../code_executors/built_in_code_executor.js");
38
- var import_code_execution_utils = require("../code_executors/code_execution_utils.js");
39
- var import_code_executor_context = require("../code_executors/code_executor_context.js");
40
32
  var import_event = require("../events/event.js");
41
- var import_event_actions = require("../events/event_actions.js");
42
33
  var import_base_llm = require("../models/base_llm.js");
43
- var import_llm_request = require("../models/llm_request.js");
44
34
  var import_registry = require("../models/registry.js");
45
- var import_state = require("../sessions/state.js");
46
35
  var import_base_tool = require("../tools/base_tool.js");
47
- var import_function_tool = require("../tools/function_tool.js");
48
- var import_tool_confirmation = require("../tools/tool_confirmation.js");
49
- var import_tool_context = require("../tools/tool_context.js");
50
- var import_env_aware_utils = require("../utils/env_aware_utils.js");
51
36
  var import_logger = require("../utils/logger.js");
37
+ var import_context = require("./context.js");
52
38
  var import_tracing = require("../telemetry/tracing.js");
39
+ var import_simple_zod_to_json = require("../utils/simple_zod_to_json.js");
53
40
  var import_base_agent = require("./base_agent.js");
54
- var import_base_llm_processor = require("./base_llm_processor.js");
55
- var import_callback_context = require("./callback_context.js");
56
- var import_content_processor_utils = require("./content_processor_utils.js");
57
41
  var import_functions = require("./functions.js");
58
- var import_instructions = require("./instructions.js");
42
+ var import_agent_transfer_llm_request_processor = require("./processors/agent_transfer_llm_request_processor.js");
43
+ var import_basic_llm_request_processor = require("./processors/basic_llm_request_processor.js");
44
+ var import_code_execution_request_processor = require("./processors/code_execution_request_processor.js");
45
+ var import_content_request_processor = require("./processors/content_request_processor.js");
46
+ var import_identity_llm_request_processor = require("./processors/identity_llm_request_processor.js");
47
+ var import_instructions_llm_request_processor = require("./processors/instructions_llm_request_processor.js");
48
+ var import_request_confirmation_llm_request_processor = require("./processors/request_confirmation_llm_request_processor.js");
59
49
  var import_readonly_context = require("./readonly_context.js");
60
50
  var import_run_config = require("./run_config.js");
61
51
  /**
@@ -66,651 +56,11 @@ var import_run_config = require("./run_config.js");
66
56
  var _a, _b;
67
57
  const ADK_AGENT_NAME_LABEL_KEY = "adk_agent_name";
68
58
  async function convertToolUnionToTools(toolUnion, context2) {
69
- if (toolUnion instanceof import_base_tool.BaseTool) {
59
+ if ((0, import_base_tool.isBaseTool)(toolUnion)) {
70
60
  return [toolUnion];
71
61
  }
72
62
  return await toolUnion.getTools(context2);
73
63
  }
74
- class BasicLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
75
- // eslint-disable-next-line require-yield
76
- async *runAsync(invocationContext, llmRequest) {
77
- var _a2;
78
- const agent = invocationContext.agent;
79
- if (!isLlmAgent(agent)) {
80
- return;
81
- }
82
- llmRequest.model = agent.canonicalModel.model;
83
- llmRequest.config = { ...(_a2 = agent.generateContentConfig) != null ? _a2 : {} };
84
- if (agent.outputSchema) {
85
- (0, import_llm_request.setOutputSchema)(llmRequest, agent.outputSchema);
86
- }
87
- if (invocationContext.runConfig) {
88
- llmRequest.liveConnectConfig.responseModalities = invocationContext.runConfig.responseModalities;
89
- llmRequest.liveConnectConfig.speechConfig = invocationContext.runConfig.speechConfig;
90
- llmRequest.liveConnectConfig.outputAudioTranscription = invocationContext.runConfig.outputAudioTranscription;
91
- llmRequest.liveConnectConfig.inputAudioTranscription = invocationContext.runConfig.inputAudioTranscription;
92
- llmRequest.liveConnectConfig.realtimeInputConfig = invocationContext.runConfig.realtimeInputConfig;
93
- llmRequest.liveConnectConfig.enableAffectiveDialog = invocationContext.runConfig.enableAffectiveDialog;
94
- llmRequest.liveConnectConfig.proactivity = invocationContext.runConfig.proactivity;
95
- }
96
- }
97
- }
98
- const BASIC_LLM_REQUEST_PROCESSOR = new BasicLlmRequestProcessor();
99
- class IdentityLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
100
- // eslint-disable-next-line require-yield
101
- async *runAsync(invocationContext, llmRequest) {
102
- const agent = invocationContext.agent;
103
- const si = [`You are an agent. Your internal name is "${agent.name}".`];
104
- if (agent.description) {
105
- si.push(`The description about you is "${agent.description}"`);
106
- }
107
- (0, import_llm_request.appendInstructions)(llmRequest, si);
108
- }
109
- }
110
- const IDENTITY_LLM_REQUEST_PROCESSOR = new IdentityLlmRequestProcessor();
111
- class InstructionsLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
112
- /**
113
- * Handles instructions and global instructions for LLM flow.
114
- */
115
- // eslint-disable-next-line require-yield
116
- async *runAsync(invocationContext, llmRequest) {
117
- const agent = invocationContext.agent;
118
- if (!(agent instanceof LlmAgent) || !(agent.rootAgent instanceof LlmAgent)) {
119
- return;
120
- }
121
- const rootAgent = agent.rootAgent;
122
- if (isLlmAgent(rootAgent) && rootAgent.globalInstruction) {
123
- const { instruction, requireStateInjection } = await rootAgent.canonicalGlobalInstruction(
124
- new import_readonly_context.ReadonlyContext(invocationContext)
125
- );
126
- let instructionWithState = instruction;
127
- if (requireStateInjection) {
128
- instructionWithState = await (0, import_instructions.injectSessionState)(
129
- instruction,
130
- new import_readonly_context.ReadonlyContext(invocationContext)
131
- );
132
- }
133
- (0, import_llm_request.appendInstructions)(llmRequest, [instructionWithState]);
134
- }
135
- if (agent.instruction) {
136
- const { instruction, requireStateInjection } = await agent.canonicalInstruction(
137
- new import_readonly_context.ReadonlyContext(invocationContext)
138
- );
139
- let instructionWithState = instruction;
140
- if (requireStateInjection) {
141
- instructionWithState = await (0, import_instructions.injectSessionState)(
142
- instruction,
143
- new import_readonly_context.ReadonlyContext(invocationContext)
144
- );
145
- }
146
- (0, import_llm_request.appendInstructions)(llmRequest, [instructionWithState]);
147
- }
148
- }
149
- }
150
- const INSTRUCTIONS_LLM_REQUEST_PROCESSOR = new InstructionsLlmRequestProcessor();
151
- class ContentRequestProcessor {
152
- // eslint-disable-next-line require-yield
153
- async *runAsync(invocationContext, llmRequest) {
154
- const agent = invocationContext.agent;
155
- if (!agent || !isLlmAgent(agent)) {
156
- return;
157
- }
158
- if (agent.includeContents === "default") {
159
- llmRequest.contents = (0, import_content_processor_utils.getContents)(
160
- invocationContext.session.events,
161
- agent.name,
162
- invocationContext.branch
163
- );
164
- } else {
165
- llmRequest.contents = (0, import_content_processor_utils.getCurrentTurnContents)(
166
- invocationContext.session.events,
167
- agent.name,
168
- invocationContext.branch
169
- );
170
- }
171
- return;
172
- }
173
- }
174
- const CONTENT_REQUEST_PROCESSOR = new ContentRequestProcessor();
175
- class AgentTransferLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
176
- constructor() {
177
- super(...arguments);
178
- this.toolName = "transfer_to_agent";
179
- this.tool = new import_function_tool.FunctionTool({
180
- name: this.toolName,
181
- description: "Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",
182
- parameters: import_zod.z.object({
183
- agentName: import_zod.z.string().describe("the agent name to transfer to.")
184
- }),
185
- execute: function(args, toolContext) {
186
- if (!toolContext) {
187
- throw new Error("toolContext is required.");
188
- }
189
- toolContext.actions.transferToAgent = args.agentName;
190
- return "Transfer queued";
191
- }
192
- });
193
- }
194
- // eslint-disable-next-line require-yield
195
- async *runAsync(invocationContext, llmRequest) {
196
- if (!(invocationContext.agent instanceof LlmAgent)) {
197
- return;
198
- }
199
- const transferTargets = this.getTransferTargets(invocationContext.agent);
200
- if (!transferTargets.length) {
201
- return;
202
- }
203
- (0, import_llm_request.appendInstructions)(llmRequest, [
204
- this.buildTargetAgentsInstructions(
205
- invocationContext.agent,
206
- transferTargets
207
- )
208
- ]);
209
- const toolContext = new import_tool_context.ToolContext({ invocationContext });
210
- await this.tool.processLlmRequest({ toolContext, llmRequest });
211
- }
212
- buildTargetAgentsInfo(targetAgent) {
213
- return `
214
- Agent name: ${targetAgent.name}
215
- Agent description: ${targetAgent.description}
216
- `;
217
- }
218
- buildTargetAgentsInstructions(agent, targetAgents) {
219
- let instructions = `
220
- You have a list of other agents to transfer to:
221
-
222
- ${targetAgents.map(this.buildTargetAgentsInfo).join("\n")}
223
-
224
- If you are the best to answer the question according to your description, you
225
- can answer it.
226
-
227
- If another agent is better for answering the question according to its
228
- description, call \`${this.toolName}\` function to transfer the
229
- question to that agent. When transferring, do not generate any text other than
230
- the function call.
231
- `;
232
- if (agent.parentAgent && !agent.disallowTransferToParent) {
233
- instructions += `
234
- Your parent agent is ${agent.parentAgent.name}. If neither the other agents nor
235
- you are best for answering the question according to the descriptions, transfer
236
- to your parent agent.
237
- `;
238
- }
239
- return instructions;
240
- }
241
- getTransferTargets(agent) {
242
- const targets = [];
243
- targets.push(...agent.subAgents);
244
- if (!agent.parentAgent || !isLlmAgent(agent.parentAgent)) {
245
- return targets;
246
- }
247
- if (!agent.disallowTransferToParent) {
248
- targets.push(agent.parentAgent);
249
- }
250
- if (!agent.disallowTransferToPeers) {
251
- targets.push(
252
- ...agent.parentAgent.subAgents.filter(
253
- (peerAgent) => peerAgent.name !== agent.name
254
- )
255
- );
256
- }
257
- return targets;
258
- }
259
- }
260
- const AGENT_TRANSFER_LLM_REQUEST_PROCESSOR = new AgentTransferLlmRequestProcessor();
261
- class RequestConfirmationLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
262
- /** Handles tool confirmation information to build the LLM request. */
263
- async *runAsync(invocationContext) {
264
- const agent = invocationContext.agent;
265
- if (!isLlmAgent(agent)) {
266
- return;
267
- }
268
- const events = invocationContext.session.events;
269
- if (!events || events.length === 0) {
270
- return;
271
- }
272
- const requestConfirmationFunctionResponses = {};
273
- let confirmationEventIndex = -1;
274
- for (let i = events.length - 1; i >= 0; i--) {
275
- const event = events[i];
276
- if (event.author !== "user") {
277
- continue;
278
- }
279
- const responses = (0, import_event.getFunctionResponses)(event);
280
- if (!responses) {
281
- continue;
282
- }
283
- let foundConfirmation = false;
284
- for (const functionResponse of responses) {
285
- if (functionResponse.name !== import_functions.REQUEST_CONFIRMATION_FUNCTION_CALL_NAME) {
286
- continue;
287
- }
288
- foundConfirmation = true;
289
- let toolConfirmation = null;
290
- if (functionResponse.response && Object.keys(functionResponse.response).length === 1 && "response" in functionResponse.response) {
291
- toolConfirmation = JSON.parse(
292
- functionResponse.response["response"]
293
- );
294
- } else if (functionResponse.response) {
295
- toolConfirmation = new import_tool_confirmation.ToolConfirmation({
296
- hint: functionResponse.response["hint"],
297
- payload: functionResponse.response["payload"],
298
- confirmed: functionResponse.response["confirmed"]
299
- });
300
- }
301
- if (functionResponse.id && toolConfirmation) {
302
- requestConfirmationFunctionResponses[functionResponse.id] = toolConfirmation;
303
- }
304
- }
305
- if (foundConfirmation) {
306
- confirmationEventIndex = i;
307
- break;
308
- }
309
- }
310
- if (Object.keys(requestConfirmationFunctionResponses).length === 0) {
311
- return;
312
- }
313
- for (let i = confirmationEventIndex - 1; i >= 0; i--) {
314
- const event = events[i];
315
- const functionCalls = (0, import_event.getFunctionCalls)(event);
316
- if (!functionCalls) {
317
- continue;
318
- }
319
- const toolsToResumeWithConfirmation = {};
320
- const toolsToResumeWithArgs = {};
321
- for (const functionCall of functionCalls) {
322
- if (!functionCall.id || !(functionCall.id in requestConfirmationFunctionResponses)) {
323
- continue;
324
- }
325
- const args = functionCall.args;
326
- if (!args || !("originalFunctionCall" in args)) {
327
- continue;
328
- }
329
- const originalFunctionCall = args["originalFunctionCall"];
330
- if (originalFunctionCall.id) {
331
- toolsToResumeWithConfirmation[originalFunctionCall.id] = requestConfirmationFunctionResponses[functionCall.id];
332
- toolsToResumeWithArgs[originalFunctionCall.id] = originalFunctionCall;
333
- }
334
- }
335
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
336
- continue;
337
- }
338
- for (let j = events.length - 1; j > confirmationEventIndex; j--) {
339
- const eventToCheck = events[j];
340
- const functionResponses = (0, import_event.getFunctionResponses)(eventToCheck);
341
- if (!functionResponses) {
342
- continue;
343
- }
344
- for (const fr of functionResponses) {
345
- if (fr.id && fr.id in toolsToResumeWithConfirmation) {
346
- delete toolsToResumeWithConfirmation[fr.id];
347
- delete toolsToResumeWithArgs[fr.id];
348
- }
349
- }
350
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
351
- break;
352
- }
353
- }
354
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
355
- continue;
356
- }
357
- const toolsList = await agent.canonicalTools(
358
- new import_readonly_context.ReadonlyContext(invocationContext)
359
- );
360
- const toolsDict = Object.fromEntries(
361
- toolsList.map((tool) => [tool.name, tool])
362
- );
363
- const functionResponseEvent = await (0, import_functions.handleFunctionCallList)({
364
- invocationContext,
365
- functionCalls: Object.values(toolsToResumeWithArgs),
366
- toolsDict,
367
- beforeToolCallbacks: agent.canonicalBeforeToolCallbacks,
368
- afterToolCallbacks: agent.canonicalAfterToolCallbacks,
369
- filters: new Set(Object.keys(toolsToResumeWithConfirmation)),
370
- toolConfirmationDict: toolsToResumeWithConfirmation
371
- });
372
- if (functionResponseEvent) {
373
- yield functionResponseEvent;
374
- }
375
- return;
376
- }
377
- }
378
- }
379
- const REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR = new RequestConfirmationLlmRequestProcessor();
380
- class CodeExecutionRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
381
- async *runAsync(invocationContext, llmRequest) {
382
- if (!(invocationContext.agent instanceof LlmAgent)) {
383
- return;
384
- }
385
- if (!invocationContext.agent.codeExecutor) {
386
- return;
387
- }
388
- for await (const event of runPreProcessor(invocationContext, llmRequest)) {
389
- yield event;
390
- }
391
- if (!(0, import_base_code_executor.isBaseCodeExecutor)(invocationContext.agent.codeExecutor)) {
392
- return;
393
- }
394
- for (const content of llmRequest.contents) {
395
- const delimeters = invocationContext.agent.codeExecutor.codeBlockDelimiters.length ? invocationContext.agent.codeExecutor.codeBlockDelimiters[0] : ["", ""];
396
- (0, import_code_execution_utils.convertCodeExecutionParts)(
397
- content,
398
- delimeters,
399
- invocationContext.agent.codeExecutor.executionResultDelimiters
400
- );
401
- }
402
- }
403
- }
404
- const DATA_FILE_UTIL_MAP = {
405
- "text/csv": {
406
- extension: ".csv",
407
- loaderCodeTemplate: "pd.read_csv('{filename}')"
408
- }
409
- };
410
- const DATA_FILE_HELPER_LIB = `
411
- import pandas as pd
412
-
413
- def explore_df(df: pd.DataFrame) -> None:
414
- """Prints some information about a pandas DataFrame."""
415
-
416
- with pd.option_context(
417
- 'display.max_columns', None, 'display.expand_frame_repr', False
418
- ):
419
- # Print the column names to never encounter KeyError when selecting one.
420
- df_dtypes = df.dtypes
421
-
422
- # Obtain information about data types and missing values.
423
- df_nulls = (len(df) - df.isnull().sum()).apply(
424
- lambda x: f'{x} / {df.shape[0]} non-null'
425
- )
426
-
427
- # Explore unique total values in columns using \`.unique()\`.
428
- df_unique_count = df.apply(lambda x: len(x.unique()))
429
-
430
- # Explore unique values in columns using \`.unique()\`.
431
- df_unique = df.apply(lambda x: crop(str(list(x.unique()))))
432
-
433
- df_info = pd.concat(
434
- (
435
- df_dtypes.rename('Dtype'),
436
- df_nulls.rename('Non-Null Count'),
437
- df_unique_count.rename('Unique Values Count'),
438
- df_unique.rename('Unique Values'),
439
- ),
440
- axis=1,
441
- )
442
- df_info.index.name = 'Columns'
443
- print(f"""Total rows: {df.shape[0]}
444
- Total columns: {df.shape[1]}
445
-
446
- {df_info}""")
447
- `;
448
- class CodeExecutionResponseProcessor {
449
- /**
450
- * Processes the LLM response asynchronously.
451
- *
452
- * @param invocationContext The invocation context
453
- * @param llmResponse The LLM response to process
454
- * @returns An async generator yielding events
455
- */
456
- async *runAsync(invocationContext, llmResponse) {
457
- if (llmResponse.partial) {
458
- return;
459
- }
460
- for await (const event of runPostProcessor(
461
- invocationContext,
462
- llmResponse
463
- )) {
464
- yield event;
465
- }
466
- }
467
- }
468
- const responseProcessor = new CodeExecutionResponseProcessor();
469
- async function* runPreProcessor(invocationContext, llmRequest) {
470
- const agent = invocationContext.agent;
471
- if (!isLlmAgent(agent)) {
472
- return;
473
- }
474
- const codeExecutor = agent.codeExecutor;
475
- if (!codeExecutor || !(0, import_base_code_executor.isBaseCodeExecutor)(codeExecutor)) {
476
- return;
477
- }
478
- if ((0, import_built_in_code_executor.isBuiltInCodeExecutor)(codeExecutor)) {
479
- codeExecutor.processLlmRequest(llmRequest);
480
- return;
481
- }
482
- if (!codeExecutor.optimizeDataFile) {
483
- return;
484
- }
485
- const codeExecutorContext = new import_code_executor_context.CodeExecutorContext(
486
- new import_state.State(invocationContext.session.state)
487
- );
488
- if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
489
- return;
490
- }
491
- const allInputFiles = extractAndReplaceInlineFiles(
492
- codeExecutorContext,
493
- llmRequest
494
- );
495
- const processedFileNames = new Set(
496
- codeExecutorContext.getProcessedFileNames()
497
- );
498
- const filesToProcess = allInputFiles.filter(
499
- (f) => !processedFileNames.has(f.name)
500
- );
501
- for (const file of filesToProcess) {
502
- const codeStr = getDataFilePreprocessingCode(file);
503
- if (!codeStr) {
504
- return;
505
- }
506
- const codeContent = {
507
- role: "model",
508
- parts: [
509
- { text: `Processing input file: \`${file.name}\`` },
510
- (0, import_code_execution_utils.buildExecutableCodePart)(codeStr)
511
- ]
512
- };
513
- llmRequest.contents.push((0, import_lodash_es.cloneDeep)(codeContent));
514
- yield (0, import_event.createEvent)({
515
- invocationId: invocationContext.invocationId,
516
- author: agent.name,
517
- branch: invocationContext.branch,
518
- content: codeContent
519
- });
520
- const executionId = getOrSetExecutionId(
521
- invocationContext,
522
- codeExecutorContext
523
- );
524
- const codeExecutionResult = await codeExecutor.executeCode({
525
- invocationContext,
526
- codeExecutionInput: {
527
- code: codeStr,
528
- inputFiles: [file],
529
- executionId
530
- }
531
- });
532
- codeExecutorContext.updateCodeExecutionResult({
533
- invocationId: invocationContext.invocationId,
534
- code: codeStr,
535
- resultStdout: codeExecutionResult.stdout,
536
- resultStderr: codeExecutionResult.stderr
537
- });
538
- codeExecutorContext.addProcessedFileNames([file.name]);
539
- const executionResultEvent = await postProcessCodeExecutionResult(
540
- invocationContext,
541
- codeExecutorContext,
542
- codeExecutionResult
543
- );
544
- yield executionResultEvent;
545
- llmRequest.contents.push((0, import_lodash_es.cloneDeep)(executionResultEvent.content));
546
- }
547
- }
548
- async function* runPostProcessor(invocationContext, llmResponse) {
549
- const agent = invocationContext.agent;
550
- if (!isLlmAgent(agent)) {
551
- return;
552
- }
553
- const codeExecutor = agent.codeExecutor;
554
- if (!codeExecutor || !(0, import_base_code_executor.isBaseCodeExecutor)(codeExecutor)) {
555
- return;
556
- }
557
- if (!llmResponse || !llmResponse.content) {
558
- return;
559
- }
560
- if ((0, import_built_in_code_executor.isBuiltInCodeExecutor)(codeExecutor)) {
561
- return;
562
- }
563
- const codeExecutorContext = new import_code_executor_context.CodeExecutorContext(
564
- new import_state.State(invocationContext.session.state)
565
- );
566
- if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
567
- return;
568
- }
569
- const responseContent = llmResponse.content;
570
- const codeStr = (0, import_code_execution_utils.extractCodeAndTruncateContent)(
571
- responseContent,
572
- codeExecutor.codeBlockDelimiters
573
- );
574
- if (!codeStr) {
575
- return;
576
- }
577
- yield (0, import_event.createEvent)({
578
- invocationId: invocationContext.invocationId,
579
- author: agent.name,
580
- branch: invocationContext.branch,
581
- content: responseContent
582
- });
583
- const executionId = getOrSetExecutionId(
584
- invocationContext,
585
- codeExecutorContext
586
- );
587
- const codeExecutionResult = await codeExecutor.executeCode({
588
- invocationContext,
589
- codeExecutionInput: {
590
- code: codeStr,
591
- inputFiles: codeExecutorContext.getInputFiles(),
592
- executionId
593
- }
594
- });
595
- codeExecutorContext.updateCodeExecutionResult({
596
- invocationId: invocationContext.invocationId,
597
- code: codeStr,
598
- resultStdout: codeExecutionResult.stdout,
599
- resultStderr: codeExecutionResult.stderr
600
- });
601
- yield await postProcessCodeExecutionResult(
602
- invocationContext,
603
- codeExecutorContext,
604
- codeExecutionResult
605
- );
606
- llmResponse.content = void 0;
607
- }
608
- function extractAndReplaceInlineFiles(codeExecutorContext, llmRequest) {
609
- var _a2;
610
- const allInputFiles = codeExecutorContext.getInputFiles();
611
- const savedFileNames = new Set(allInputFiles.map((f) => f.name));
612
- for (let i = 0; i < llmRequest.contents.length; i++) {
613
- const content = llmRequest.contents[i];
614
- if (content.role !== "user" || !content.parts) {
615
- continue;
616
- }
617
- for (let j = 0; j < content.parts.length; j++) {
618
- const part = content.parts[j];
619
- const mimeType = (_a2 = part.inlineData) == null ? void 0 : _a2.mimeType;
620
- if (!mimeType || !part.inlineData || !DATA_FILE_UTIL_MAP[mimeType]) {
621
- continue;
622
- }
623
- const fileName = `data_${i + 1}_${j + 1}${DATA_FILE_UTIL_MAP[mimeType].extension}`;
624
- part.text = `
625
- Available file: \`${fileName}\`
626
- `;
627
- const file = {
628
- name: fileName,
629
- content: (0, import_env_aware_utils.base64Decode)(part.inlineData.data),
630
- mimeType
631
- };
632
- if (!savedFileNames.has(fileName)) {
633
- codeExecutorContext.addInputFiles([file]);
634
- allInputFiles.push(file);
635
- }
636
- }
637
- }
638
- return allInputFiles;
639
- }
640
- function getOrSetExecutionId(invocationContext, codeExecutorContext) {
641
- var _a2;
642
- const agent = invocationContext.agent;
643
- if (!isLlmAgent(agent) || !((_a2 = agent.codeExecutor) == null ? void 0 : _a2.stateful)) {
644
- return void 0;
645
- }
646
- let executionId = codeExecutorContext.getExecutionId();
647
- if (!executionId) {
648
- executionId = invocationContext.session.id;
649
- codeExecutorContext.setExecutionId(executionId);
650
- }
651
- return executionId;
652
- }
653
- async function postProcessCodeExecutionResult(invocationContext, codeExecutorContext, codeExecutionResult) {
654
- if (!invocationContext.artifactService) {
655
- throw new Error("Artifact service is not initialized.");
656
- }
657
- const resultContent = {
658
- role: "model",
659
- parts: [(0, import_code_execution_utils.buildCodeExecutionResultPart)(codeExecutionResult)]
660
- };
661
- const eventActions = (0, import_event_actions.createEventActions)({
662
- stateDelta: codeExecutorContext.getStateDelta()
663
- });
664
- if (codeExecutionResult.stderr) {
665
- codeExecutorContext.incrementErrorCount(invocationContext.invocationId);
666
- } else {
667
- codeExecutorContext.resetErrorCount(invocationContext.invocationId);
668
- }
669
- for (const outputFile of codeExecutionResult.outputFiles) {
670
- const version = await invocationContext.artifactService.saveArtifact({
671
- appName: invocationContext.appName || "",
672
- userId: invocationContext.userId || "",
673
- sessionId: invocationContext.session.id,
674
- filename: outputFile.name,
675
- artifact: {
676
- inlineData: { data: outputFile.content, mimeType: outputFile.mimeType }
677
- }
678
- });
679
- eventActions.artifactDelta[outputFile.name] = version;
680
- }
681
- return (0, import_event.createEvent)({
682
- invocationId: invocationContext.invocationId,
683
- author: invocationContext.agent.name,
684
- branch: invocationContext.branch,
685
- content: resultContent,
686
- actions: eventActions
687
- });
688
- }
689
- function getDataFilePreprocessingCode(file) {
690
- function getNormalizedFileName(fileName) {
691
- const [varName2] = fileName.split(".");
692
- let normalizedName = varName2.replace(/[^a-zA-Z0-9_]/g, "_");
693
- if (/^\d/.test(normalizedName)) {
694
- normalizedName = "_" + normalizedName;
695
- }
696
- return normalizedName;
697
- }
698
- if (!DATA_FILE_UTIL_MAP[file.mimeType]) {
699
- return void 0;
700
- }
701
- const varName = getNormalizedFileName(file.name);
702
- const loaderCode = DATA_FILE_UTIL_MAP[file.mimeType].loaderCodeTemplate.replace("{filename}", file.name);
703
- return `
704
- ${DATA_FILE_HELPER_LIB}
705
-
706
- # Load the dataframe.
707
- ${varName} = ${loaderCode}
708
-
709
- # Use \`explore_df\` to guide my analysis.
710
- explore_df(${varName})
711
- `;
712
- }
713
- const CODE_EXECUTION_REQUEST_PROCESSOR = new CodeExecutionRequestProcessor();
714
64
  const LLM_AGENT_SIGNATURE_SYMBOL = Symbol.for("google.adk.llmAgent");
715
65
  function isLlmAgent(obj) {
716
66
  return typeof obj === "object" && obj !== null && LLM_AGENT_SIGNATURE_SYMBOL in obj && obj[LLM_AGENT_SIGNATURE_SYMBOL] === true;
@@ -729,8 +79,8 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
729
79
  this.disallowTransferToParent = (_d = config.disallowTransferToParent) != null ? _d : false;
730
80
  this.disallowTransferToPeers = (_e = config.disallowTransferToPeers) != null ? _e : false;
731
81
  this.includeContents = (_f = config.includeContents) != null ? _f : "default";
732
- this.inputSchema = config.inputSchema;
733
- this.outputSchema = config.outputSchema;
82
+ this.inputSchema = (0, import_simple_zod_to_json.isZodObject)(config.inputSchema) ? (0, import_simple_zod_to_json.zodObjectToSchema)(config.inputSchema) : config.inputSchema;
83
+ this.outputSchema = (0, import_simple_zod_to_json.isZodObject)(config.outputSchema) ? (0, import_simple_zod_to_json.zodObjectToSchema)(config.outputSchema) : config.outputSchema;
734
84
  this.outputKey = config.outputKey;
735
85
  this.beforeModelCallback = config.beforeModelCallback;
736
86
  this.afterModelCallback = config.afterModelCallback;
@@ -738,17 +88,17 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
738
88
  this.afterToolCallback = config.afterToolCallback;
739
89
  this.codeExecutor = config.codeExecutor;
740
90
  this.requestProcessors = (_g = config.requestProcessors) != null ? _g : [
741
- BASIC_LLM_REQUEST_PROCESSOR,
742
- IDENTITY_LLM_REQUEST_PROCESSOR,
743
- INSTRUCTIONS_LLM_REQUEST_PROCESSOR,
744
- REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
745
- CONTENT_REQUEST_PROCESSOR,
746
- CODE_EXECUTION_REQUEST_PROCESSOR
91
+ import_basic_llm_request_processor.BASIC_LLM_REQUEST_PROCESSOR,
92
+ import_identity_llm_request_processor.IDENTITY_LLM_REQUEST_PROCESSOR,
93
+ import_instructions_llm_request_processor.INSTRUCTIONS_LLM_REQUEST_PROCESSOR,
94
+ import_request_confirmation_llm_request_processor.REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
95
+ import_content_request_processor.CONTENT_REQUEST_PROCESSOR,
96
+ import_code_execution_request_processor.CODE_EXECUTION_REQUEST_PROCESSOR
747
97
  ];
748
98
  this.responseProcessors = (_h = config.responseProcessors) != null ? _h : [];
749
99
  const agentTransferDisabled = this.disallowTransferToParent && this.disallowTransferToPeers && !((_i = this.subAgents) == null ? void 0 : _i.length);
750
100
  if (!agentTransferDisabled) {
751
- this.requestProcessors.push(AGENT_TRANSFER_LLM_REQUEST_PROCESSOR);
101
+ this.requestProcessors.push(import_agent_transfer_llm_request_processor.AGENT_TRANSFER_LLM_REQUEST_PROCESSOR);
752
102
  }
753
103
  if (config.generateContentConfig) {
754
104
  if (config.generateContentConfig.tools) {
@@ -775,16 +125,6 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
775
125
  this.disallowTransferToParent = true;
776
126
  this.disallowTransferToPeers = true;
777
127
  }
778
- if (this.subAgents && this.subAgents.length > 0) {
779
- throw new Error(
780
- `Invalid config for agent ${this.name}: if outputSchema is set, subAgents must be empty to disable agent transfer.`
781
- );
782
- }
783
- if (this.tools && this.tools.length > 0) {
784
- throw new Error(
785
- `Invalid config for agent ${this.name}: if outputSchema is set, tools must be empty`
786
- );
787
- }
788
128
  }
789
129
  }
790
130
  /**
@@ -1005,7 +345,7 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1005
345
  }
1006
346
  }
1007
347
  for (const toolUnion of this.tools) {
1008
- const toolContext = new import_tool_context.ToolContext({ invocationContext });
348
+ const toolContext = new import_context.Context({ invocationContext });
1009
349
  const tools = await convertToolUnionToTools(
1010
350
  toolUnion,
1011
351
  new import_readonly_context.ReadonlyContext(invocationContext)
@@ -1028,28 +368,36 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1028
368
  ctx,
1029
369
  this,
1030
370
  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(
371
+ const responsesGenerator = async function* () {
372
+ for await (const llmResponse of this.callLlmAsync(
1037
373
  invocationContext,
1038
374
  llmRequest,
1039
- llmResponse,
1040
375
  modelResponseEvent
1041
376
  )) {
1042
- modelResponseEvent.id = (0, import_event.createNewEventId)();
1043
- modelResponseEvent.timestamp = (/* @__PURE__ */ new Date()).getTime();
1044
- yield event;
377
+ for await (const event of this.postprocess(
378
+ invocationContext,
379
+ llmRequest,
380
+ llmResponse,
381
+ modelResponseEvent
382
+ )) {
383
+ modelResponseEvent.id = (0, import_event.createNewEventId)();
384
+ modelResponseEvent.timestamp = (/* @__PURE__ */ new Date()).getTime();
385
+ yield event;
386
+ }
1045
387
  }
1046
- }
388
+ };
389
+ yield* this.runAndHandleError(
390
+ responsesGenerator.call(this),
391
+ invocationContext,
392
+ llmRequest,
393
+ modelResponseEvent
394
+ );
1047
395
  }
1048
396
  );
1049
397
  span.end();
1050
398
  }
1051
399
  async *postprocess(invocationContext, llmRequest, llmResponse, modelResponseEvent) {
1052
- var _a2;
400
+ var _a2, _b2;
1053
401
  for (const processor of this.responseProcessors) {
1054
402
  for await (const event of processor.runAsync(
1055
403
  invocationContext,
@@ -1078,6 +426,10 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1078
426
  if (!((_a2 = (0, import_event.getFunctionCalls)(mergedEvent)) == null ? void 0 : _a2.length)) {
1079
427
  return;
1080
428
  }
429
+ if ((_b2 = invocationContext.runConfig) == null ? void 0 : _b2.pauseOnToolCalls) {
430
+ invocationContext.endInvocation = true;
431
+ return;
432
+ }
1081
433
  const functionResponseEvent = await (0, import_functions.handleFunctionCallsAsync)({
1082
434
  invocationContext,
1083
435
  functionCallEvent: mergedEvent,
@@ -1102,6 +454,8 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1102
454
  });
1103
455
  if (toolConfirmationEvent) {
1104
456
  yield toolConfirmationEvent;
457
+ invocationContext.endInvocation = true;
458
+ return;
1105
459
  }
1106
460
  yield functionResponseEvent;
1107
461
  const nextAgentName = functionResponseEvent.actions.transferToAgent;
@@ -1158,12 +512,7 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1158
512
  /* stream= */
1159
513
  ((_e = invocationContext.runConfig) == null ? void 0 : _e.streamingMode) === import_run_config.StreamingMode.SSE
1160
514
  );
1161
- for await (const llmResponse of this.runAndHandleError(
1162
- responsesGenerator,
1163
- invocationContext,
1164
- llmRequest,
1165
- modelResponseEvent
1166
- )) {
515
+ for await (const llmResponse of responsesGenerator) {
1167
516
  (0, import_tracing.traceCallLlm)({
1168
517
  invocationContext,
1169
518
  eventId: modelResponseEvent.id,
@@ -1180,7 +529,7 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1180
529
  }
1181
530
  }
1182
531
  async handleBeforeModelCallback(invocationContext, llmRequest, modelResponseEvent) {
1183
- const callbackContext = new import_callback_context.CallbackContext({
532
+ const callbackContext = new import_context.Context({
1184
533
  invocationContext,
1185
534
  eventActions: modelResponseEvent.actions
1186
535
  });
@@ -1203,7 +552,7 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1203
552
  return void 0;
1204
553
  }
1205
554
  async handleAfterModelCallback(invocationContext, llmResponse, modelResponseEvent) {
1206
- const callbackContext = new import_callback_context.CallbackContext({
555
+ const callbackContext = new import_context.Context({
1207
556
  invocationContext,
1208
557
  eventActions: modelResponseEvent.actions
1209
558
  });
@@ -1231,7 +580,7 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1231
580
  yield response;
1232
581
  }
1233
582
  } catch (modelError) {
1234
- const callbackContext = new import_callback_context.CallbackContext({
583
+ const callbackContext = new import_context.Context({
1235
584
  invocationContext,
1236
585
  eventActions: modelResponseEvent.actions
1237
586
  });
@@ -1244,11 +593,29 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1244
593
  if (onModelErrorCallbackResponse) {
1245
594
  yield onModelErrorCallbackResponse;
1246
595
  } else {
1247
- const errorResponse = JSON.parse(modelError.message);
1248
- yield {
1249
- errorCode: String(errorResponse.error.code),
1250
- errorMessage: errorResponse.error.message
1251
- };
596
+ let errorCode = "UNKNOWN_ERROR";
597
+ let errorMessage = modelError.message;
598
+ try {
599
+ const errorResponse = JSON.parse(modelError.message);
600
+ if (errorResponse == null ? void 0 : errorResponse.error) {
601
+ errorCode = String(errorResponse.error.code || "UNKNOWN_ERROR");
602
+ errorMessage = errorResponse.error.message || errorMessage;
603
+ }
604
+ } catch {
605
+ }
606
+ if (modelResponseEvent.actions) {
607
+ yield (0, import_event.createEvent)({
608
+ invocationId: invocationContext.invocationId,
609
+ author: this.name,
610
+ errorCode,
611
+ errorMessage
612
+ });
613
+ } else {
614
+ yield {
615
+ errorCode,
616
+ errorMessage
617
+ };
618
+ }
1252
619
  }
1253
620
  } else {
1254
621
  import_logger.logger.error("Unknown error during response generation", modelError);
@@ -1266,7 +633,5 @@ class LlmAgent extends (_b = import_base_agent.BaseAgent, _a = LLM_AGENT_SIGNATU
1266
633
  // Annotate the CommonJS export names for ESM import in node:
1267
634
  0 && (module.exports = {
1268
635
  LlmAgent,
1269
- REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
1270
- isLlmAgent,
1271
- responseProcessor
636
+ isLlmAgent
1272
637
  });