@google/adk 0.1.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 (311) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +9 -0
  3. package/dist/cjs/agents/active_streaming_tool.js +44 -0
  4. package/dist/cjs/agents/base_agent.js +245 -0
  5. package/dist/cjs/agents/base_llm_processor.js +44 -0
  6. package/dist/cjs/agents/callback_context.js +98 -0
  7. package/dist/cjs/agents/content_processor_utils.js +299 -0
  8. package/dist/cjs/agents/functions.js +394 -0
  9. package/dist/cjs/agents/instructions.js +110 -0
  10. package/dist/cjs/agents/invocation_context.js +109 -0
  11. package/dist/cjs/agents/live_request_queue.js +136 -0
  12. package/dist/cjs/agents/llm_agent.js +859 -0
  13. package/dist/cjs/agents/loop_agent.js +68 -0
  14. package/dist/cjs/agents/parallel_agent.js +78 -0
  15. package/dist/cjs/agents/readonly_context.js +68 -0
  16. package/dist/cjs/agents/run_config.js +74 -0
  17. package/dist/cjs/agents/sequential_agent.js +84 -0
  18. package/dist/cjs/agents/transcription_entry.js +27 -0
  19. package/dist/cjs/artifacts/base_artifact_service.js +27 -0
  20. package/dist/cjs/artifacts/in_memory_artifact_service.js +119 -0
  21. package/dist/cjs/auth/auth_credential.js +46 -0
  22. package/dist/cjs/auth/auth_handler.js +92 -0
  23. package/dist/cjs/auth/auth_schemes.js +62 -0
  24. package/dist/cjs/auth/auth_tool.js +27 -0
  25. package/dist/cjs/auth/credential_service/base_credential_service.js +27 -0
  26. package/dist/cjs/auth/credential_service/in_memory_credential_service.js +63 -0
  27. package/dist/cjs/code_executors/base_code_executor.js +76 -0
  28. package/dist/cjs/code_executors/built_in_code_executor.js +58 -0
  29. package/dist/cjs/code_executors/code_execution_utils.js +142 -0
  30. package/dist/cjs/code_executors/code_executor_context.js +198 -0
  31. package/dist/cjs/common.js +161 -0
  32. package/dist/cjs/events/event.js +107 -0
  33. package/dist/cjs/events/event_actions.js +83 -0
  34. package/dist/cjs/examples/base_example_provider.js +40 -0
  35. package/dist/cjs/examples/example.js +27 -0
  36. package/dist/cjs/examples/example_util.js +107 -0
  37. package/dist/cjs/index.js +40 -0
  38. package/dist/cjs/index.js.map +7 -0
  39. package/dist/cjs/index_web.js +33 -0
  40. package/dist/cjs/memory/base_memory_service.js +27 -0
  41. package/dist/cjs/memory/in_memory_memory_service.js +97 -0
  42. package/dist/cjs/memory/memory_entry.js +27 -0
  43. package/dist/cjs/models/base_llm.js +77 -0
  44. package/dist/cjs/models/base_llm_connection.js +27 -0
  45. package/dist/cjs/models/gemini_llm_connection.js +132 -0
  46. package/dist/cjs/models/google_llm.js +321 -0
  47. package/dist/cjs/models/llm_request.js +82 -0
  48. package/dist/cjs/models/llm_response.js +71 -0
  49. package/dist/cjs/models/registry.js +121 -0
  50. package/dist/cjs/package.json +1 -0
  51. package/dist/cjs/plugins/base_plugin.js +236 -0
  52. package/dist/cjs/plugins/logging_plugin.js +222 -0
  53. package/dist/cjs/plugins/plugin_manager.js +239 -0
  54. package/dist/cjs/plugins/security_plugin.js +153 -0
  55. package/dist/cjs/runner/in_memory_runner.js +58 -0
  56. package/dist/cjs/runner/runner.js +276 -0
  57. package/dist/cjs/sessions/base_session_service.js +71 -0
  58. package/dist/cjs/sessions/in_memory_session_service.js +184 -0
  59. package/dist/cjs/sessions/session.js +48 -0
  60. package/dist/cjs/sessions/state.js +101 -0
  61. package/dist/cjs/tools/agent_tool.js +134 -0
  62. package/dist/cjs/tools/base_tool.js +107 -0
  63. package/dist/cjs/tools/base_toolset.js +76 -0
  64. package/dist/cjs/tools/forwarding_artifact_service.js +71 -0
  65. package/dist/cjs/tools/function_tool.js +101 -0
  66. package/dist/cjs/tools/google_search_tool.js +76 -0
  67. package/dist/cjs/tools/long_running_tool.js +63 -0
  68. package/dist/cjs/tools/mcp/mcp_session_manager.js +65 -0
  69. package/dist/cjs/tools/mcp/mcp_tool.js +65 -0
  70. package/dist/cjs/tools/mcp/mcp_toolset.js +61 -0
  71. package/dist/cjs/tools/tool_confirmation.js +49 -0
  72. package/dist/cjs/tools/tool_context.js +129 -0
  73. package/dist/cjs/utils/deep_clone.js +44 -0
  74. package/dist/cjs/utils/env_aware_utils.js +83 -0
  75. package/dist/cjs/utils/gemini_schema_util.js +88 -0
  76. package/dist/cjs/utils/logger.js +121 -0
  77. package/dist/cjs/utils/model_name.js +64 -0
  78. package/dist/cjs/utils/simple_zod_to_json.js +191 -0
  79. package/dist/cjs/utils/variant_utils.js +55 -0
  80. package/dist/cjs/version.js +39 -0
  81. package/dist/esm/agents/active_streaming_tool.js +14 -0
  82. package/dist/esm/agents/base_agent.js +214 -0
  83. package/dist/esm/agents/base_llm_processor.js +13 -0
  84. package/dist/esm/agents/callback_context.js +68 -0
  85. package/dist/esm/agents/content_processor_utils.js +268 -0
  86. package/dist/esm/agents/functions.js +353 -0
  87. package/dist/esm/agents/instructions.js +80 -0
  88. package/dist/esm/agents/invocation_context.js +78 -0
  89. package/dist/esm/agents/live_request_queue.js +106 -0
  90. package/dist/esm/agents/llm_agent.js +828 -0
  91. package/dist/esm/agents/loop_agent.js +38 -0
  92. package/dist/esm/agents/parallel_agent.js +48 -0
  93. package/dist/esm/agents/readonly_context.js +38 -0
  94. package/dist/esm/agents/run_config.js +43 -0
  95. package/dist/esm/agents/sequential_agent.js +54 -0
  96. package/dist/esm/agents/transcription_entry.js +5 -0
  97. package/dist/esm/artifacts/base_artifact_service.js +5 -0
  98. package/dist/esm/artifacts/in_memory_artifact_service.js +89 -0
  99. package/dist/esm/auth/auth_credential.js +16 -0
  100. package/dist/esm/auth/auth_handler.js +62 -0
  101. package/dist/esm/auth/auth_schemes.js +31 -0
  102. package/dist/esm/auth/auth_tool.js +5 -0
  103. package/dist/esm/auth/credential_service/base_credential_service.js +5 -0
  104. package/dist/esm/auth/credential_service/in_memory_credential_service.js +33 -0
  105. package/dist/esm/code_executors/base_code_executor.js +46 -0
  106. package/dist/esm/code_executors/built_in_code_executor.js +28 -0
  107. package/dist/esm/code_executors/code_execution_utils.js +108 -0
  108. package/dist/esm/code_executors/code_executor_context.js +168 -0
  109. package/dist/esm/common.js +85 -0
  110. package/dist/esm/events/event.js +72 -0
  111. package/dist/esm/events/event_actions.js +52 -0
  112. package/dist/esm/examples/base_example_provider.js +10 -0
  113. package/dist/esm/examples/example.js +5 -0
  114. package/dist/esm/examples/example_util.js +76 -0
  115. package/dist/esm/index.js +40 -0
  116. package/dist/esm/index.js.map +7 -0
  117. package/dist/esm/index_web.js +6 -0
  118. package/dist/esm/memory/base_memory_service.js +5 -0
  119. package/dist/esm/memory/in_memory_memory_service.js +67 -0
  120. package/dist/esm/memory/memory_entry.js +5 -0
  121. package/dist/esm/models/base_llm.js +47 -0
  122. package/dist/esm/models/base_llm_connection.js +5 -0
  123. package/dist/esm/models/gemini_llm_connection.js +102 -0
  124. package/dist/esm/models/google_llm.js +291 -0
  125. package/dist/esm/models/llm_request.js +50 -0
  126. package/dist/esm/models/llm_response.js +41 -0
  127. package/dist/esm/models/registry.js +91 -0
  128. package/dist/esm/plugins/base_plugin.js +206 -0
  129. package/dist/esm/plugins/logging_plugin.js +192 -0
  130. package/dist/esm/plugins/plugin_manager.js +209 -0
  131. package/dist/esm/plugins/security_plugin.js +119 -0
  132. package/dist/esm/runner/in_memory_runner.js +28 -0
  133. package/dist/esm/runner/runner.js +246 -0
  134. package/dist/esm/sessions/base_session_service.js +41 -0
  135. package/dist/esm/sessions/in_memory_session_service.js +154 -0
  136. package/dist/esm/sessions/session.js +18 -0
  137. package/dist/esm/sessions/state.js +71 -0
  138. package/dist/esm/tools/agent_tool.js +104 -0
  139. package/dist/esm/tools/base_tool.js +77 -0
  140. package/dist/esm/tools/base_toolset.js +46 -0
  141. package/dist/esm/tools/forwarding_artifact_service.js +41 -0
  142. package/dist/esm/tools/function_tool.js +71 -0
  143. package/dist/esm/tools/google_search_tool.js +46 -0
  144. package/dist/esm/tools/long_running_tool.js +33 -0
  145. package/dist/esm/tools/mcp/mcp_session_manager.js +35 -0
  146. package/dist/esm/tools/mcp/mcp_tool.js +35 -0
  147. package/dist/esm/tools/mcp/mcp_toolset.js +31 -0
  148. package/dist/esm/tools/tool_confirmation.js +19 -0
  149. package/dist/esm/tools/tool_context.js +99 -0
  150. package/dist/esm/utils/deep_clone.js +14 -0
  151. package/dist/esm/utils/env_aware_utils.js +49 -0
  152. package/dist/esm/utils/gemini_schema_util.js +58 -0
  153. package/dist/esm/utils/logger.js +89 -0
  154. package/dist/esm/utils/model_name.js +31 -0
  155. package/dist/esm/utils/simple_zod_to_json.js +160 -0
  156. package/dist/esm/utils/variant_utils.js +24 -0
  157. package/dist/esm/version.js +9 -0
  158. package/dist/types/agents/active_streaming_tool.d.ts +29 -0
  159. package/dist/types/agents/base_agent.d.ts +167 -0
  160. package/dist/types/agents/base_llm_processor.d.ts +27 -0
  161. package/dist/types/agents/callback_context.d.ts +42 -0
  162. package/dist/types/agents/content_processor_utils.d.ts +36 -0
  163. package/dist/types/agents/functions.d.ts +90 -0
  164. package/dist/types/agents/instructions.d.ts +32 -0
  165. package/dist/types/agents/invocation_context.d.ts +155 -0
  166. package/dist/types/agents/live_request_queue.d.ts +67 -0
  167. package/dist/types/agents/llm_agent.d.ts +333 -0
  168. package/dist/types/agents/loop_agent.d.ts +31 -0
  169. package/dist/types/agents/parallel_agent.d.ts +21 -0
  170. package/dist/types/agents/readonly_context.d.ts +31 -0
  171. package/dist/types/agents/run_config.d.ts +76 -0
  172. package/dist/types/agents/sequential_agent.d.ts +26 -0
  173. package/dist/types/agents/transcription_entry.d.ts +17 -0
  174. package/dist/types/artifacts/base_artifact_service.d.ts +127 -0
  175. package/dist/types/artifacts/in_memory_artifact_service.d.ts +18 -0
  176. package/dist/types/auth/auth_credential.d.ts +227 -0
  177. package/dist/types/auth/auth_handler.d.ts +27 -0
  178. package/dist/types/auth/auth_schemes.d.ts +36 -0
  179. package/dist/types/auth/auth_tool.d.ts +51 -0
  180. package/dist/types/auth/credential_service/base_credential_service.d.ts +27 -0
  181. package/dist/types/auth/credential_service/in_memory_credential_service.d.ts +19 -0
  182. package/dist/types/code_executors/base_code_executor.d.ts +60 -0
  183. package/dist/types/code_executors/built_in_code_executor.d.ts +13 -0
  184. package/dist/types/code_executors/code_execution_utils.d.ts +99 -0
  185. package/dist/types/code_executors/code_executor_context.d.ts +92 -0
  186. package/dist/types/common.d.ts +51 -0
  187. package/dist/types/events/event.d.ts +81 -0
  188. package/dist/types/events/event_actions.d.ts +74 -0
  189. package/dist/types/examples/base_example_provider.d.ts +20 -0
  190. package/dist/types/examples/example.d.ts +19 -0
  191. package/dist/types/examples/example_util.d.ts +13 -0
  192. package/dist/types/index.d.ts +9 -0
  193. package/dist/types/index_web.d.ts +6 -0
  194. package/dist/types/memory/base_memory_service.d.ts +47 -0
  195. package/dist/types/memory/in_memory_memory_service.d.ts +18 -0
  196. package/dist/types/memory/memory_entry.d.ts +24 -0
  197. package/dist/types/models/base_llm.d.ts +46 -0
  198. package/dist/types/models/base_llm_connection.d.ts +51 -0
  199. package/dist/types/models/gemini_llm_connection.d.ts +54 -0
  200. package/dist/types/models/google_llm.d.ts +88 -0
  201. package/dist/types/models/llm_request.d.ts +49 -0
  202. package/dist/types/models/llm_response.d.ts +79 -0
  203. package/dist/types/models/registry.d.ts +45 -0
  204. package/dist/types/plugins/base_plugin.d.ts +310 -0
  205. package/dist/types/plugins/logging_plugin.d.ts +104 -0
  206. package/dist/types/plugins/plugin_manager.d.ts +155 -0
  207. package/dist/types/plugins/security_plugin.d.ts +60 -0
  208. package/dist/types/runner/in_memory_runner.d.ts +15 -0
  209. package/dist/types/runner/runner.d.ts +80 -0
  210. package/dist/types/sessions/base_session_service.d.ts +129 -0
  211. package/dist/types/sessions/in_memory_session_service.d.ts +32 -0
  212. package/dist/types/sessions/session.d.ts +46 -0
  213. package/dist/types/sessions/state.d.ts +57 -0
  214. package/dist/types/tools/agent_tool.d.ts +37 -0
  215. package/dist/types/tools/base_tool.d.ts +84 -0
  216. package/dist/types/tools/base_toolset.d.ts +64 -0
  217. package/dist/types/tools/forwarding_artifact_service.d.ts +21 -0
  218. package/dist/types/tools/function_tool.d.ts +48 -0
  219. package/dist/types/tools/google_search_tool.d.ts +18 -0
  220. package/dist/types/tools/long_running_tool.d.ts +18 -0
  221. package/dist/types/tools/mcp/mcp_session_manager.d.ts +57 -0
  222. package/dist/types/tools/mcp/mcp_tool.d.ts +30 -0
  223. package/dist/types/tools/mcp/mcp_toolset.d.ts +39 -0
  224. package/dist/types/tools/tool_confirmation.d.ts +25 -0
  225. package/dist/types/tools/tool_context.d.ts +63 -0
  226. package/dist/types/utils/deep_clone.d.ts +1 -0
  227. package/dist/types/utils/env_aware_utils.d.ts +31 -0
  228. package/dist/types/utils/gemini_schema_util.d.ts +23 -0
  229. package/dist/types/utils/logger.d.ts +41 -0
  230. package/dist/types/utils/model_name.d.ts +34 -0
  231. package/dist/types/utils/simple_zod_to_json.d.ts +12 -0
  232. package/dist/types/utils/variant_utils.d.ts +24 -0
  233. package/dist/types/version.d.ts +6 -0
  234. package/dist/web/agents/active_streaming_tool.js +14 -0
  235. package/dist/web/agents/base_agent.js +265 -0
  236. package/dist/web/agents/base_llm_processor.js +13 -0
  237. package/dist/web/agents/callback_context.js +68 -0
  238. package/dist/web/agents/content_processor_utils.js +268 -0
  239. package/dist/web/agents/functions.js +353 -0
  240. package/dist/web/agents/instructions.js +80 -0
  241. package/dist/web/agents/invocation_context.js +78 -0
  242. package/dist/web/agents/live_request_queue.js +124 -0
  243. package/dist/web/agents/llm_agent.js +973 -0
  244. package/dist/web/agents/loop_agent.js +71 -0
  245. package/dist/web/agents/parallel_agent.js +83 -0
  246. package/dist/web/agents/readonly_context.js +38 -0
  247. package/dist/web/agents/run_config.js +43 -0
  248. package/dist/web/agents/sequential_agent.js +99 -0
  249. package/dist/web/agents/transcription_entry.js +5 -0
  250. package/dist/web/artifacts/base_artifact_service.js +5 -0
  251. package/dist/web/artifacts/in_memory_artifact_service.js +89 -0
  252. package/dist/web/auth/auth_credential.js +16 -0
  253. package/dist/web/auth/auth_handler.js +62 -0
  254. package/dist/web/auth/auth_schemes.js +31 -0
  255. package/dist/web/auth/auth_tool.js +5 -0
  256. package/dist/web/auth/credential_service/base_credential_service.js +5 -0
  257. package/dist/web/auth/credential_service/in_memory_credential_service.js +33 -0
  258. package/dist/web/code_executors/base_code_executor.js +46 -0
  259. package/dist/web/code_executors/built_in_code_executor.js +28 -0
  260. package/dist/web/code_executors/code_execution_utils.js +105 -0
  261. package/dist/web/code_executors/code_executor_context.js +168 -0
  262. package/dist/web/common.js +85 -0
  263. package/dist/web/events/event.js +90 -0
  264. package/dist/web/events/event_actions.js +67 -0
  265. package/dist/web/examples/base_example_provider.js +10 -0
  266. package/dist/web/examples/example.js +5 -0
  267. package/dist/web/examples/example_util.js +75 -0
  268. package/dist/web/index.js +13 -0
  269. package/dist/web/index.js.map +7 -0
  270. package/dist/web/index_web.js +6 -0
  271. package/dist/web/memory/base_memory_service.js +5 -0
  272. package/dist/web/memory/in_memory_memory_service.js +67 -0
  273. package/dist/web/memory/memory_entry.js +5 -0
  274. package/dist/web/models/base_llm.js +47 -0
  275. package/dist/web/models/base_llm_connection.js +5 -0
  276. package/dist/web/models/gemini_llm_connection.js +120 -0
  277. package/dist/web/models/google_llm.js +332 -0
  278. package/dist/web/models/llm_request.js +50 -0
  279. package/dist/web/models/llm_response.js +41 -0
  280. package/dist/web/models/registry.js +91 -0
  281. package/dist/web/plugins/base_plugin.js +206 -0
  282. package/dist/web/plugins/logging_plugin.js +192 -0
  283. package/dist/web/plugins/plugin_manager.js +209 -0
  284. package/dist/web/plugins/security_plugin.js +119 -0
  285. package/dist/web/runner/in_memory_runner.js +28 -0
  286. package/dist/web/runner/runner.js +277 -0
  287. package/dist/web/sessions/base_session_service.js +41 -0
  288. package/dist/web/sessions/in_memory_session_service.js +154 -0
  289. package/dist/web/sessions/session.js +18 -0
  290. package/dist/web/sessions/state.js +87 -0
  291. package/dist/web/tools/agent_tool.js +118 -0
  292. package/dist/web/tools/base_tool.js +77 -0
  293. package/dist/web/tools/base_toolset.js +46 -0
  294. package/dist/web/tools/forwarding_artifact_service.js +41 -0
  295. package/dist/web/tools/function_tool.js +71 -0
  296. package/dist/web/tools/google_search_tool.js +46 -0
  297. package/dist/web/tools/long_running_tool.js +50 -0
  298. package/dist/web/tools/mcp/mcp_session_manager.js +35 -0
  299. package/dist/web/tools/mcp/mcp_tool.js +35 -0
  300. package/dist/web/tools/mcp/mcp_toolset.js +31 -0
  301. package/dist/web/tools/tool_confirmation.js +19 -0
  302. package/dist/web/tools/tool_context.js +99 -0
  303. package/dist/web/utils/deep_clone.js +14 -0
  304. package/dist/web/utils/env_aware_utils.js +49 -0
  305. package/dist/web/utils/gemini_schema_util.js +58 -0
  306. package/dist/web/utils/logger.js +89 -0
  307. package/dist/web/utils/model_name.js +31 -0
  308. package/dist/web/utils/simple_zod_to_json.js +174 -0
  309. package/dist/web/utils/variant_utils.js +24 -0
  310. package/dist/web/version.js +9 -0
  311. package/package.json +61 -0
@@ -0,0 +1,859 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+ var llm_agent_exports = {};
26
+ __export(llm_agent_exports, {
27
+ LlmAgent: () => LlmAgent,
28
+ REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR: () => REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR
29
+ });
30
+ module.exports = __toCommonJS(llm_agent_exports);
31
+ var import_zod = require("zod");
32
+ var import_event = require("../events/event.js");
33
+ var import_base_llm = require("../models/base_llm.js");
34
+ var import_llm_request = require("../models/llm_request.js");
35
+ var import_registry = require("../models/registry.js");
36
+ var import_base_tool = require("../tools/base_tool.js");
37
+ var import_function_tool = require("../tools/function_tool.js");
38
+ var import_tool_confirmation = require("../tools/tool_confirmation.js");
39
+ var import_tool_context = require("../tools/tool_context.js");
40
+ var import_logger = require("../utils/logger.js");
41
+ var import_base_agent = require("./base_agent.js");
42
+ var import_base_llm_processor = require("./base_llm_processor.js");
43
+ var import_callback_context = require("./callback_context.js");
44
+ var import_content_processor_utils = require("./content_processor_utils.js");
45
+ var import_functions = require("./functions.js");
46
+ var import_instructions = require("./instructions.js");
47
+ var import_readonly_context = require("./readonly_context.js");
48
+ /**
49
+ * @license
50
+ * Copyright 2025 Google LLC
51
+ * SPDX-License-Identifier: Apache-2.0
52
+ */
53
+ const ADK_AGENT_NAME_LABEL_KEY = "adk_agent_name";
54
+ async function convertToolUnionToTools(toolUnion, context) {
55
+ if (toolUnion instanceof import_base_tool.BaseTool) {
56
+ return [toolUnion];
57
+ }
58
+ return await toolUnion.getTools(context);
59
+ }
60
+ class BasicLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
61
+ async *runAsync(invocationContext, llmRequest) {
62
+ var _a;
63
+ const agent = invocationContext.agent;
64
+ if (!(agent instanceof LlmAgent)) {
65
+ return;
66
+ }
67
+ llmRequest.model = agent.canonicalModel.model;
68
+ llmRequest.config = { ...(_a = agent.generateContentConfig) != null ? _a : {} };
69
+ if (agent.outputSchema) {
70
+ (0, import_llm_request.setOutputSchema)(llmRequest, agent.outputSchema);
71
+ }
72
+ if (invocationContext.runConfig) {
73
+ llmRequest.liveConnectConfig.responseModalities = invocationContext.runConfig.responseModalities;
74
+ llmRequest.liveConnectConfig.speechConfig = invocationContext.runConfig.speechConfig;
75
+ llmRequest.liveConnectConfig.outputAudioTranscription = invocationContext.runConfig.outputAudioTranscription;
76
+ llmRequest.liveConnectConfig.inputAudioTranscription = invocationContext.runConfig.inputAudioTranscription;
77
+ llmRequest.liveConnectConfig.realtimeInputConfig = invocationContext.runConfig.realtimeInputConfig;
78
+ llmRequest.liveConnectConfig.enableAffectiveDialog = invocationContext.runConfig.enableAffectiveDialog;
79
+ llmRequest.liveConnectConfig.proactivity = invocationContext.runConfig.proactivity;
80
+ }
81
+ }
82
+ }
83
+ const BASIC_LLM_REQUEST_PROCESSOR = new BasicLlmRequestProcessor();
84
+ class IdentityLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
85
+ async *runAsync(invocationContext, llmRequest) {
86
+ const agent = invocationContext.agent;
87
+ const si = [`You are an agent. Your internal name is "${agent.name}".`];
88
+ if (agent.description) {
89
+ si.push(`The description about you is "${agent.description}"`);
90
+ }
91
+ (0, import_llm_request.appendInstructions)(llmRequest, si);
92
+ }
93
+ }
94
+ const IDENTITY_LLM_REQUEST_PROCESSOR = new IdentityLlmRequestProcessor();
95
+ class InstructionsLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
96
+ /**
97
+ * Handles instructions and global instructions for LLM flow.
98
+ */
99
+ async *runAsync(invocationContext, llmRequest) {
100
+ const agent = invocationContext.agent;
101
+ if (!(agent instanceof LlmAgent) || !(agent.rootAgent instanceof LlmAgent)) {
102
+ return;
103
+ }
104
+ const rootAgent = agent.rootAgent;
105
+ if (rootAgent instanceof LlmAgent && rootAgent.globalInstruction) {
106
+ const { instruction, requireStateInjection } = await rootAgent.canonicalGlobalInstruction(
107
+ new import_readonly_context.ReadonlyContext(invocationContext)
108
+ );
109
+ let instructionWithState = instruction;
110
+ if (requireStateInjection) {
111
+ instructionWithState = await (0, import_instructions.injectSessionState)(
112
+ instruction,
113
+ new import_readonly_context.ReadonlyContext(invocationContext)
114
+ );
115
+ }
116
+ (0, import_llm_request.appendInstructions)(llmRequest, [instructionWithState]);
117
+ }
118
+ if (agent.instruction) {
119
+ const { instruction, requireStateInjection } = await agent.canonicalInstruction(
120
+ new import_readonly_context.ReadonlyContext(invocationContext)
121
+ );
122
+ let instructionWithState = instruction;
123
+ if (requireStateInjection) {
124
+ instructionWithState = await (0, import_instructions.injectSessionState)(
125
+ instruction,
126
+ new import_readonly_context.ReadonlyContext(invocationContext)
127
+ );
128
+ }
129
+ (0, import_llm_request.appendInstructions)(llmRequest, [instructionWithState]);
130
+ }
131
+ }
132
+ }
133
+ const INSTRUCTIONS_LLM_REQUEST_PROCESSOR = new InstructionsLlmRequestProcessor();
134
+ class ContentRequestProcessor {
135
+ async *runAsync(invocationContext, llmRequest) {
136
+ const agent = invocationContext.agent;
137
+ if (!agent || !(agent instanceof LlmAgent)) {
138
+ return;
139
+ }
140
+ if (agent.includeContents === "default") {
141
+ llmRequest.contents = (0, import_content_processor_utils.getContents)(
142
+ invocationContext.session.events,
143
+ agent.name,
144
+ invocationContext.branch
145
+ );
146
+ } else {
147
+ llmRequest.contents = (0, import_content_processor_utils.getCurrentTurnContents)(
148
+ invocationContext.session.events,
149
+ agent.name,
150
+ invocationContext.branch
151
+ );
152
+ }
153
+ return;
154
+ }
155
+ }
156
+ const CONTENT_REQUEST_PROCESSOR = new ContentRequestProcessor();
157
+ class AgentTransferLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
158
+ constructor() {
159
+ super(...arguments);
160
+ this.toolName = "transfer_to_agent";
161
+ this.tool = new import_function_tool.FunctionTool({
162
+ name: this.toolName,
163
+ 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.",
164
+ parameters: import_zod.z.object({
165
+ agentName: import_zod.z.string().describe("the agent name to transfer to.")
166
+ }),
167
+ execute: function(args, toolContext) {
168
+ if (!toolContext) {
169
+ throw new Error("toolContext is required.");
170
+ }
171
+ toolContext.actions.transferToAgent = args.agentName;
172
+ }
173
+ });
174
+ }
175
+ async *runAsync(invocationContext, llmRequest) {
176
+ if (!(invocationContext.agent instanceof LlmAgent)) {
177
+ return;
178
+ }
179
+ const transferTargets = this.getTransferTargets(invocationContext.agent);
180
+ if (!transferTargets.length) {
181
+ return;
182
+ }
183
+ (0, import_llm_request.appendInstructions)(llmRequest, [
184
+ this.buildTargetAgentsInstructions(
185
+ invocationContext.agent,
186
+ transferTargets
187
+ )
188
+ ]);
189
+ const toolContext = new import_tool_context.ToolContext({ invocationContext });
190
+ await this.tool.processLlmRequest({ toolContext, llmRequest });
191
+ }
192
+ buildTargetAgentsInfo(targetAgent) {
193
+ return `
194
+ Agent name: ${targetAgent.name}
195
+ Agent description: ${targetAgent.description}
196
+ `;
197
+ }
198
+ buildTargetAgentsInstructions(agent, targetAgents) {
199
+ let instructions = `
200
+ You have a list of other agents to transfer to:
201
+
202
+ ${targetAgents.map(this.buildTargetAgentsInfo).join("\n")}
203
+
204
+ If you are the best to answer the question according to your description, you
205
+ can answer it.
206
+
207
+ If another agent is better for answering the question according to its
208
+ description, call \`${this.toolName}\` function to transfer the
209
+ question to that agent. When transferring, do not generate any text other than
210
+ the function call.
211
+ `;
212
+ if (agent.parentAgent && !agent.disallowTransferToParent) {
213
+ instructions += `
214
+ Your parent agent is ${agent.parentAgent.name}. If neither the other agents nor
215
+ you are best for answering the question according to the descriptions, transfer
216
+ to your parent agent.
217
+ `;
218
+ }
219
+ return instructions;
220
+ }
221
+ getTransferTargets(agent) {
222
+ const targets = [];
223
+ targets.push(...agent.subAgents);
224
+ if (!agent.parentAgent || !(agent.parentAgent instanceof LlmAgent)) {
225
+ return targets;
226
+ }
227
+ if (!agent.disallowTransferToParent) {
228
+ targets.push(agent.parentAgent);
229
+ }
230
+ if (!agent.disallowTransferToPeers) {
231
+ targets.push(
232
+ ...agent.parentAgent.subAgents.filter(
233
+ (peerAgent) => peerAgent.name !== agent.name
234
+ )
235
+ );
236
+ }
237
+ return targets;
238
+ }
239
+ }
240
+ const AGENT_TRANSFER_LLM_REQUEST_PROCESSOR = new AgentTransferLlmRequestProcessor();
241
+ class RequestConfirmationLlmRequestProcessor extends import_base_llm_processor.BaseLlmRequestProcessor {
242
+ /** Handles tool confirmation information to build the LLM request. */
243
+ async *runAsync(invocationContext, llmRequest) {
244
+ const agent = invocationContext.agent;
245
+ if (!(agent instanceof LlmAgent)) {
246
+ return;
247
+ }
248
+ const events = invocationContext.session.events;
249
+ if (!events || events.length === 0) {
250
+ return;
251
+ }
252
+ const requestConfirmationFunctionResponses = {};
253
+ let confirmationEventIndex = -1;
254
+ for (let i = events.length - 1; i >= 0; i--) {
255
+ const event = events[i];
256
+ if (event.author !== "user") {
257
+ continue;
258
+ }
259
+ const responses = (0, import_event.getFunctionResponses)(event);
260
+ if (!responses) {
261
+ continue;
262
+ }
263
+ let foundConfirmation = false;
264
+ for (const functionResponse of responses) {
265
+ if (functionResponse.name !== import_functions.REQUEST_CONFIRMATION_FUNCTION_CALL_NAME) {
266
+ continue;
267
+ }
268
+ foundConfirmation = true;
269
+ let toolConfirmation = null;
270
+ if (functionResponse.response && Object.keys(functionResponse.response).length === 1 && "response" in functionResponse.response) {
271
+ toolConfirmation = JSON.parse(functionResponse.response["response"]);
272
+ } else if (functionResponse.response) {
273
+ toolConfirmation = new import_tool_confirmation.ToolConfirmation({
274
+ hint: functionResponse.response["hint"],
275
+ payload: functionResponse.response["payload"],
276
+ confirmed: functionResponse.response["confirmed"]
277
+ });
278
+ }
279
+ if (functionResponse.id && toolConfirmation) {
280
+ requestConfirmationFunctionResponses[functionResponse.id] = toolConfirmation;
281
+ }
282
+ }
283
+ if (foundConfirmation) {
284
+ confirmationEventIndex = i;
285
+ break;
286
+ }
287
+ }
288
+ if (Object.keys(requestConfirmationFunctionResponses).length === 0) {
289
+ return;
290
+ }
291
+ for (let i = confirmationEventIndex - 1; i >= 0; i--) {
292
+ const event = events[i];
293
+ const functionCalls = (0, import_event.getFunctionCalls)(event);
294
+ if (!functionCalls) {
295
+ continue;
296
+ }
297
+ const toolsToResumeWithConfirmation = {};
298
+ const toolsToResumeWithArgs = {};
299
+ for (const functionCall of functionCalls) {
300
+ if (!functionCall.id || !(functionCall.id in requestConfirmationFunctionResponses)) {
301
+ continue;
302
+ }
303
+ const args = functionCall.args;
304
+ if (!args || !("originalFunctionCall" in args)) {
305
+ continue;
306
+ }
307
+ const originalFunctionCall = args["originalFunctionCall"];
308
+ if (originalFunctionCall.id) {
309
+ toolsToResumeWithConfirmation[originalFunctionCall.id] = requestConfirmationFunctionResponses[functionCall.id];
310
+ toolsToResumeWithArgs[originalFunctionCall.id] = originalFunctionCall;
311
+ }
312
+ }
313
+ if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
314
+ continue;
315
+ }
316
+ for (let j = events.length - 1; j > confirmationEventIndex; j--) {
317
+ const eventToCheck = events[j];
318
+ const functionResponses = (0, import_event.getFunctionResponses)(eventToCheck);
319
+ if (!functionResponses) {
320
+ continue;
321
+ }
322
+ for (const fr of functionResponses) {
323
+ if (fr.id && fr.id in toolsToResumeWithConfirmation) {
324
+ delete toolsToResumeWithConfirmation[fr.id];
325
+ delete toolsToResumeWithArgs[fr.id];
326
+ }
327
+ }
328
+ if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
329
+ break;
330
+ }
331
+ }
332
+ if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
333
+ continue;
334
+ }
335
+ const toolsList = await agent.canonicalTools(new import_readonly_context.ReadonlyContext(invocationContext));
336
+ const toolsDict = Object.fromEntries(toolsList.map((tool) => [tool.name, tool]));
337
+ const functionResponseEvent = await (0, import_functions.handleFunctionCallList)({
338
+ invocationContext,
339
+ functionCalls: Object.values(toolsToResumeWithArgs),
340
+ toolsDict,
341
+ beforeToolCallbacks: agent.canonicalBeforeToolCallbacks,
342
+ afterToolCallbacks: agent.canonicalAfterToolCallbacks,
343
+ filters: new Set(Object.keys(toolsToResumeWithConfirmation)),
344
+ toolConfirmationDict: toolsToResumeWithConfirmation
345
+ });
346
+ if (functionResponseEvent) {
347
+ yield functionResponseEvent;
348
+ }
349
+ return;
350
+ }
351
+ }
352
+ }
353
+ const REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR = new RequestConfirmationLlmRequestProcessor();
354
+ class LlmAgent extends import_base_agent.BaseAgent {
355
+ constructor(config) {
356
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
357
+ super(config);
358
+ this.model = config.model;
359
+ this.instruction = (_a = config.instruction) != null ? _a : "";
360
+ this.globalInstruction = (_b = config.globalInstruction) != null ? _b : "";
361
+ this.tools = (_c = config.tools) != null ? _c : [];
362
+ this.generateContentConfig = config.generateContentConfig;
363
+ this.disallowTransferToParent = (_d = config.disallowTransferToParent) != null ? _d : false;
364
+ this.disallowTransferToPeers = (_e = config.disallowTransferToPeers) != null ? _e : false;
365
+ this.includeContents = (_f = config.includeContents) != null ? _f : "default";
366
+ this.inputSchema = config.inputSchema;
367
+ this.outputSchema = config.outputSchema;
368
+ this.outputKey = config.outputKey;
369
+ this.beforeModelCallback = config.beforeModelCallback;
370
+ this.afterModelCallback = config.afterModelCallback;
371
+ this.beforeToolCallback = config.beforeToolCallback;
372
+ this.afterToolCallback = config.afterToolCallback;
373
+ this.requestProcessors = (_g = config.requestProcessors) != null ? _g : [
374
+ BASIC_LLM_REQUEST_PROCESSOR,
375
+ IDENTITY_LLM_REQUEST_PROCESSOR,
376
+ INSTRUCTIONS_LLM_REQUEST_PROCESSOR,
377
+ REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
378
+ CONTENT_REQUEST_PROCESSOR
379
+ ];
380
+ this.responseProcessors = (_h = config.responseProcessors) != null ? _h : [];
381
+ const agentTransferDisabled = this.disallowTransferToParent && this.disallowTransferToPeers && !((_i = this.subAgents) == null ? void 0 : _i.length);
382
+ if (!agentTransferDisabled) {
383
+ this.requestProcessors.push(AGENT_TRANSFER_LLM_REQUEST_PROCESSOR);
384
+ }
385
+ if (config.generateContentConfig) {
386
+ if (config.generateContentConfig.tools) {
387
+ throw new Error("All tools must be set via LlmAgent.tools.");
388
+ }
389
+ if (config.generateContentConfig.systemInstruction) {
390
+ throw new Error(
391
+ "System instruction must be set via LlmAgent.instruction."
392
+ );
393
+ }
394
+ if (config.generateContentConfig.responseSchema) {
395
+ throw new Error(
396
+ "Response schema must be set via LlmAgent.output_schema."
397
+ );
398
+ }
399
+ } else {
400
+ this.generateContentConfig = {};
401
+ }
402
+ if (this.outputSchema) {
403
+ if (!this.disallowTransferToParent || !this.disallowTransferToPeers) {
404
+ import_logger.logger.warn(
405
+ `Invalid config for agent ${this.name}: outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true`
406
+ );
407
+ this.disallowTransferToParent = true;
408
+ this.disallowTransferToPeers = true;
409
+ }
410
+ if (this.subAgents && this.subAgents.length > 0) {
411
+ throw new Error(
412
+ `Invalid config for agent ${this.name}: if outputSchema is set, subAgents must be empty to disable agent transfer.`
413
+ );
414
+ }
415
+ if (this.tools && this.tools.length > 0) {
416
+ throw new Error(
417
+ `Invalid config for agent ${this.name}: if outputSchema is set, tools must be empty`
418
+ );
419
+ }
420
+ }
421
+ }
422
+ /**
423
+ * The resolved BaseLlm instance.
424
+ *
425
+ * When not set, the agent will inherit the model from its ancestor.
426
+ */
427
+ get canonicalModel() {
428
+ if (this.model instanceof import_base_llm.BaseLlm) {
429
+ return this.model;
430
+ }
431
+ if (typeof this.model === "string" && this.model) {
432
+ return import_registry.LLMRegistry.newLlm(this.model);
433
+ }
434
+ let ancestorAgent = this.parentAgent;
435
+ while (ancestorAgent) {
436
+ if (ancestorAgent instanceof LlmAgent) {
437
+ return ancestorAgent.canonicalModel;
438
+ }
439
+ ancestorAgent = ancestorAgent.parentAgent;
440
+ }
441
+ throw new Error(`No model found for ${this.name}.`);
442
+ }
443
+ /**
444
+ * The resolved self.instruction field to construct instruction for this
445
+ * agent.
446
+ *
447
+ * This method is only for use by Agent Development Kit.
448
+ * @param context The context to retrieve the session state.
449
+ * @returns The resolved self.instruction field.
450
+ */
451
+ async canonicalInstruction(context) {
452
+ if (typeof this.instruction === "string") {
453
+ return { instruction: this.instruction, requireStateInjection: true };
454
+ }
455
+ return {
456
+ instruction: await this.instruction(context),
457
+ requireStateInjection: false
458
+ };
459
+ }
460
+ /**
461
+ * The resolved self.instruction field to construct global instruction.
462
+ *
463
+ * This method is only for use by Agent Development Kit.
464
+ * @param context The context to retrieve the session state.
465
+ * @returns The resolved self.global_instruction field.
466
+ */
467
+ async canonicalGlobalInstruction(context) {
468
+ if (typeof this.globalInstruction === "string") {
469
+ return { instruction: this.globalInstruction, requireStateInjection: true };
470
+ }
471
+ return {
472
+ instruction: await this.globalInstruction(context),
473
+ requireStateInjection: false
474
+ };
475
+ }
476
+ /**
477
+ * The resolved self.tools field as a list of BaseTool based on the context.
478
+ *
479
+ * This method is only for use by Agent Development Kit.
480
+ */
481
+ async canonicalTools(context) {
482
+ const resolvedTools = [];
483
+ for (const toolUnion of this.tools) {
484
+ const tools = await convertToolUnionToTools(toolUnion, context);
485
+ resolvedTools.push(...tools);
486
+ }
487
+ return resolvedTools;
488
+ }
489
+ /**
490
+ * Normalizes a callback or an array of callbacks into an array of callbacks.
491
+ *
492
+ * @param callback The callback or an array of callbacks.
493
+ * @returns An array of callbacks.
494
+ */
495
+ static normalizeCallbackArray(callback) {
496
+ if (!callback) {
497
+ return [];
498
+ }
499
+ if (Array.isArray(callback)) {
500
+ return callback;
501
+ }
502
+ return [callback];
503
+ }
504
+ /**
505
+ * The resolved self.before_model_callback field as a list of
506
+ * SingleBeforeModelCallback.
507
+ *
508
+ * This method is only for use by Agent Development Kit.
509
+ */
510
+ get canonicalBeforeModelCallbacks() {
511
+ return LlmAgent.normalizeCallbackArray(this.beforeModelCallback);
512
+ }
513
+ /**
514
+ * The resolved self.after_model_callback field as a list of
515
+ * SingleAfterModelCallback.
516
+ *
517
+ * This method is only for use by Agent Development Kit.
518
+ */
519
+ get canonicalAfterModelCallbacks() {
520
+ return LlmAgent.normalizeCallbackArray(this.afterModelCallback);
521
+ }
522
+ /**
523
+ * The resolved self.before_tool_callback field as a list of
524
+ * BeforeToolCallback.
525
+ *
526
+ * This method is only for use by Agent Development Kit.
527
+ */
528
+ get canonicalBeforeToolCallbacks() {
529
+ return LlmAgent.normalizeCallbackArray(this.beforeToolCallback);
530
+ }
531
+ /**
532
+ * The resolved self.after_tool_callback field as a list of AfterToolCallback.
533
+ *
534
+ * This method is only for use by Agent Development Kit.
535
+ */
536
+ get canonicalAfterToolCallbacks() {
537
+ return LlmAgent.normalizeCallbackArray(this.afterToolCallback);
538
+ }
539
+ /**
540
+ * Saves the agent's final response to the session state if configured.
541
+ *
542
+ * It extracts the text content from the final response event, optionally
543
+ * parses it as JSON based on the output schema, and stores the result in the
544
+ * session state using the specified output key.
545
+ *
546
+ * @param event The event to process.
547
+ */
548
+ maybeSaveOutputToState(event) {
549
+ var _a, _b;
550
+ if (event.author !== this.name) {
551
+ import_logger.logger.debug(
552
+ `Skipping output save for agent ${this.name}: event authored by ${event.author}`
553
+ );
554
+ return;
555
+ }
556
+ if (!this.outputKey) {
557
+ import_logger.logger.debug(
558
+ `Skipping output save for agent ${this.name}: outputKey is not set`
559
+ );
560
+ return;
561
+ }
562
+ if (!(0, import_event.isFinalResponse)(event)) {
563
+ import_logger.logger.debug(
564
+ `Skipping output save for agent ${this.name}: event is not a final response`
565
+ );
566
+ return;
567
+ }
568
+ if (!((_b = (_a = event.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.length)) {
569
+ import_logger.logger.debug(
570
+ `Skipping output save for agent ${this.name}: event content is empty`
571
+ );
572
+ return;
573
+ }
574
+ const resultStr = event.content.parts.map((part) => part.text ? part.text : "").join("");
575
+ let result = resultStr;
576
+ if (this.outputSchema) {
577
+ if (!resultStr.trim()) {
578
+ return;
579
+ }
580
+ try {
581
+ result = JSON.parse(resultStr);
582
+ } catch (e) {
583
+ import_logger.logger.error(`Error parsing output for agent ${this.name}`, e);
584
+ }
585
+ }
586
+ event.actions.stateDelta[this.outputKey] = result;
587
+ }
588
+ async *runAsyncImpl(context) {
589
+ while (true) {
590
+ let lastEvent = void 0;
591
+ for await (const event of this.runOneStepAsync(context)) {
592
+ lastEvent = event;
593
+ this.maybeSaveOutputToState(event);
594
+ yield event;
595
+ }
596
+ if (!lastEvent || (0, import_event.isFinalResponse)(lastEvent)) {
597
+ break;
598
+ }
599
+ if (lastEvent.partial) {
600
+ import_logger.logger.warn("The last event is partial, which is not expected.");
601
+ break;
602
+ }
603
+ }
604
+ }
605
+ async *runLiveImpl(context) {
606
+ for await (const event of this.runLiveFlow(context)) {
607
+ this.maybeSaveOutputToState(event);
608
+ yield event;
609
+ }
610
+ if (context.endInvocation) {
611
+ return;
612
+ }
613
+ }
614
+ // --------------------------------------------------------------------------
615
+ // #START LlmFlow Logic
616
+ // --------------------------------------------------------------------------
617
+ async *runLiveFlow(invocationContext) {
618
+ await Promise.resolve();
619
+ throw new Error("LlmAgent.runLiveFlow not implemented");
620
+ }
621
+ async *runOneStepAsync(invocationContext) {
622
+ const llmRequest = {
623
+ contents: [],
624
+ toolsDict: {},
625
+ liveConnectConfig: {}
626
+ };
627
+ for (const processor of this.requestProcessors) {
628
+ for await (const event of processor.runAsync(invocationContext, llmRequest)) {
629
+ yield event;
630
+ }
631
+ }
632
+ for (const toolUnion of this.tools) {
633
+ const toolContext = new import_tool_context.ToolContext({ invocationContext });
634
+ const tools = await convertToolUnionToTools(
635
+ toolUnion,
636
+ new import_readonly_context.ReadonlyContext(invocationContext)
637
+ );
638
+ for (const tool of tools) {
639
+ await tool.processLlmRequest({ toolContext, llmRequest });
640
+ }
641
+ }
642
+ if (invocationContext.endInvocation) {
643
+ return;
644
+ }
645
+ const modelResponseEvent = (0, import_event.createEvent)({
646
+ invocationId: invocationContext.invocationId,
647
+ author: this.name,
648
+ branch: invocationContext.branch
649
+ });
650
+ for await (const llmResponse of this.callLlmAsync(
651
+ invocationContext,
652
+ llmRequest,
653
+ modelResponseEvent
654
+ )) {
655
+ for await (const event of this.postprocess(
656
+ invocationContext,
657
+ llmRequest,
658
+ llmResponse,
659
+ modelResponseEvent
660
+ )) {
661
+ modelResponseEvent.id = (0, import_event.createNewEventId)();
662
+ modelResponseEvent.timestamp = (/* @__PURE__ */ new Date()).getTime();
663
+ yield event;
664
+ }
665
+ }
666
+ }
667
+ async *postprocess(invocationContext, llmRequest, llmResponse, modelResponseEvent) {
668
+ var _a;
669
+ for (const processor of this.responseProcessors) {
670
+ for await (const event of processor.runAsync(invocationContext, llmResponse)) {
671
+ yield event;
672
+ }
673
+ }
674
+ if (!llmResponse.content && !llmResponse.errorCode && !llmResponse.interrupted) {
675
+ return;
676
+ }
677
+ const mergedEvent = (0, import_event.createEvent)({
678
+ ...modelResponseEvent,
679
+ ...llmResponse
680
+ });
681
+ if (mergedEvent.content) {
682
+ const functionCalls = (0, import_event.getFunctionCalls)(mergedEvent);
683
+ if (functionCalls == null ? void 0 : functionCalls.length) {
684
+ (0, import_functions.populateClientFunctionCallId)(mergedEvent);
685
+ mergedEvent.longRunningToolIds = Array.from(
686
+ (0, import_functions.getLongRunningFunctionCalls)(functionCalls, llmRequest.toolsDict)
687
+ );
688
+ }
689
+ }
690
+ yield mergedEvent;
691
+ if (!((_a = (0, import_event.getFunctionCalls)(mergedEvent)) == null ? void 0 : _a.length)) {
692
+ return;
693
+ }
694
+ const functionResponseEvent = await (0, import_functions.handleFunctionCallsAsync)({
695
+ invocationContext,
696
+ functionCallEvent: mergedEvent,
697
+ toolsDict: llmRequest.toolsDict,
698
+ beforeToolCallbacks: this.canonicalBeforeToolCallbacks,
699
+ afterToolCallbacks: this.canonicalAfterToolCallbacks
700
+ });
701
+ if (!functionResponseEvent) {
702
+ return;
703
+ }
704
+ const authEvent = (0, import_functions.generateAuthEvent)(invocationContext, functionResponseEvent);
705
+ if (authEvent) {
706
+ yield authEvent;
707
+ }
708
+ const toolConfirmationEvent = (0, import_functions.generateRequestConfirmationEvent)({
709
+ invocationContext,
710
+ functionCallEvent: mergedEvent,
711
+ functionResponseEvent
712
+ });
713
+ if (toolConfirmationEvent) {
714
+ yield toolConfirmationEvent;
715
+ }
716
+ yield functionResponseEvent;
717
+ const nextAgentName = functionResponseEvent.actions.transferToAgent;
718
+ if (nextAgentName) {
719
+ const nextAgent = this.getAgentByName(invocationContext, nextAgentName);
720
+ for await (const event of nextAgent.runAsync(invocationContext)) {
721
+ yield event;
722
+ }
723
+ }
724
+ }
725
+ /**
726
+ * Retrieves an agent from the agent tree by its name.
727
+ *
728
+ * Performing a depth-first search to locate the agent with the given name.
729
+ * - Starts searching from the root agent of the current invocation context.
730
+ * - Traverses down the agent tree to find the specified agent.
731
+ *
732
+ * @param invocationContext The current invocation context.
733
+ * @param agentName The name of the agent to retrieve.
734
+ * @returns The agent with the given name.
735
+ * @throws Error if the agent is not found.
736
+ */
737
+ getAgentByName(invocationContext, agentName) {
738
+ const rootAgent = invocationContext.agent.rootAgent;
739
+ const agentToRun = rootAgent.findAgent(agentName);
740
+ if (!agentToRun) {
741
+ throw new Error(`Agent ${agentName} not found in the agent tree.`);
742
+ }
743
+ return agentToRun;
744
+ }
745
+ async *callLlmAsync(invocationContext, llmRequest, modelResponseEvent) {
746
+ var _a, _b, _c, _d;
747
+ const beforeModelResponse = await this.handleBeforeModelCallback(
748
+ invocationContext,
749
+ llmRequest,
750
+ modelResponseEvent
751
+ );
752
+ if (beforeModelResponse) {
753
+ yield beforeModelResponse;
754
+ return;
755
+ }
756
+ (_a = llmRequest.config) != null ? _a : llmRequest.config = {};
757
+ (_c = (_b = llmRequest.config).labels) != null ? _c : _b.labels = {};
758
+ if (!llmRequest.config.labels[ADK_AGENT_NAME_LABEL_KEY]) {
759
+ llmRequest.config.labels[ADK_AGENT_NAME_LABEL_KEY] = this.name;
760
+ }
761
+ const llm = this.canonicalModel;
762
+ if ((_d = invocationContext.runConfig) == null ? void 0 : _d.supportCfc) {
763
+ throw new Error("CFC is not yet supported in callLlmAsync");
764
+ } else {
765
+ invocationContext.incrementLlmCallCount();
766
+ const responsesGenerator = llm.generateContentAsync(llmRequest);
767
+ for await (const llmResponse of this.runAndHandleError(
768
+ responsesGenerator,
769
+ invocationContext,
770
+ llmRequest,
771
+ modelResponseEvent
772
+ )) {
773
+ const alteredLlmResponse = await this.handleAfterModelCallback(
774
+ invocationContext,
775
+ llmResponse,
776
+ modelResponseEvent
777
+ );
778
+ yield alteredLlmResponse != null ? alteredLlmResponse : llmResponse;
779
+ }
780
+ }
781
+ }
782
+ async handleBeforeModelCallback(invocationContext, llmRequest, modelResponseEvent) {
783
+ const callbackContext = new import_callback_context.CallbackContext(
784
+ { invocationContext, eventActions: modelResponseEvent.actions }
785
+ );
786
+ const beforeModelCallbackResponse = await invocationContext.pluginManager.runBeforeModelCallback(
787
+ { callbackContext, llmRequest }
788
+ );
789
+ if (beforeModelCallbackResponse) {
790
+ return beforeModelCallbackResponse;
791
+ }
792
+ for (const callback of this.canonicalBeforeModelCallbacks) {
793
+ const callbackResponse = await callback({ context: callbackContext, request: llmRequest });
794
+ if (callbackResponse) {
795
+ return callbackResponse;
796
+ }
797
+ }
798
+ return void 0;
799
+ }
800
+ async handleAfterModelCallback(invocationContext, llmResponse, modelResponseEvent) {
801
+ const callbackContext = new import_callback_context.CallbackContext(
802
+ { invocationContext, eventActions: modelResponseEvent.actions }
803
+ );
804
+ const afterModelCallbackResponse = await invocationContext.pluginManager.runAfterModelCallback(
805
+ { callbackContext, llmResponse }
806
+ );
807
+ if (afterModelCallbackResponse) {
808
+ return afterModelCallbackResponse;
809
+ }
810
+ for (const callback of this.canonicalAfterModelCallbacks) {
811
+ const callbackResponse = await callback({ context: callbackContext, response: llmResponse });
812
+ if (callbackResponse) {
813
+ return callbackResponse;
814
+ }
815
+ }
816
+ return void 0;
817
+ }
818
+ async *runAndHandleError(responseGenerator, invocationContext, llmRequest, modelResponseEvent) {
819
+ try {
820
+ for await (const response of responseGenerator) {
821
+ yield response;
822
+ }
823
+ } catch (modelError) {
824
+ const callbackContext = new import_callback_context.CallbackContext(
825
+ { invocationContext, eventActions: modelResponseEvent.actions }
826
+ );
827
+ if (modelError instanceof Error) {
828
+ const onModelErrorCallbackResponse = await invocationContext.pluginManager.runOnModelErrorCallback({
829
+ callbackContext,
830
+ llmRequest,
831
+ error: modelError
832
+ });
833
+ if (onModelErrorCallbackResponse) {
834
+ yield onModelErrorCallbackResponse;
835
+ } else {
836
+ const errorResponse = JSON.parse(modelError.message);
837
+ yield {
838
+ errorCode: String(errorResponse.error.code),
839
+ errorMessage: errorResponse.error.message
840
+ };
841
+ }
842
+ } else {
843
+ import_logger.logger.error("Unknown error during response generation", modelError);
844
+ throw modelError;
845
+ }
846
+ }
847
+ }
848
+ // --------------------------------------------------------------------------
849
+ // #END LlmFlow Logic
850
+ // --------------------------------------------------------------------------
851
+ // TODO - b/425992518: omitted Py LlmAgent features.
852
+ // - code_executor
853
+ // - configurable agents by yaml config
854
+ }
855
+ // Annotate the CommonJS export names for ESM import in node:
856
+ 0 && (module.exports = {
857
+ LlmAgent,
858
+ REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR
859
+ });