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