@google/adk 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (265) hide show
  1. package/dist/cjs/a2a/a2a_event.js +290 -0
  2. package/dist/cjs/a2a/event_converter_utils.js +201 -0
  3. package/dist/cjs/a2a/executor_context.js +53 -0
  4. package/dist/cjs/a2a/metadata_converter_utils.js +125 -0
  5. package/dist/cjs/a2a/part_converter_utils.js +212 -0
  6. package/dist/cjs/agents/active_streaming_tool.js +1 -1
  7. package/dist/cjs/agents/base_agent.js +6 -6
  8. package/dist/cjs/agents/content_processor_utils.js +1 -1
  9. package/dist/cjs/{tools/tool_context.js → agents/context.js} +71 -16
  10. package/dist/cjs/agents/functions.js +4 -3
  11. package/dist/cjs/agents/instructions.js +1 -1
  12. package/dist/cjs/agents/invocation_context.js +1 -1
  13. package/dist/cjs/agents/live_request_queue.js +1 -1
  14. package/dist/cjs/agents/llm_agent.js +76 -711
  15. package/dist/cjs/agents/loop_agent.js +1 -1
  16. package/dist/cjs/agents/parallel_agent.js +1 -1
  17. package/dist/cjs/agents/processors/agent_transfer_llm_request_processor.js +132 -0
  18. package/dist/cjs/agents/{base_llm_processor.js → processors/base_llm_processor.js} +1 -1
  19. package/dist/cjs/agents/processors/basic_llm_request_processor.js +68 -0
  20. package/dist/cjs/agents/processors/code_execution_request_processor.js +389 -0
  21. package/dist/cjs/agents/processors/content_request_processor.js +66 -0
  22. package/dist/cjs/agents/processors/identity_llm_request_processor.js +54 -0
  23. package/dist/cjs/agents/processors/instructions_llm_request_processor.js +85 -0
  24. package/dist/cjs/agents/processors/request_confirmation_llm_request_processor.js +165 -0
  25. package/dist/cjs/agents/readonly_context.js +13 -1
  26. package/dist/cjs/agents/run_config.js +2 -1
  27. package/dist/cjs/agents/sequential_agent.js +1 -1
  28. package/dist/cjs/agents/transcription_entry.js +1 -1
  29. package/dist/cjs/artifacts/base_artifact_service.js +1 -1
  30. package/dist/cjs/artifacts/file_artifact_service.js +491 -0
  31. package/dist/cjs/artifacts/gcs_artifact_service.js +127 -48
  32. package/dist/cjs/artifacts/in_memory_artifact_service.js +54 -6
  33. package/dist/cjs/artifacts/registry.js +55 -0
  34. package/dist/cjs/auth/auth_credential.js +1 -1
  35. package/dist/cjs/auth/auth_handler.js +1 -1
  36. package/dist/cjs/auth/auth_schemes.js +1 -1
  37. package/dist/cjs/auth/auth_tool.js +1 -1
  38. package/dist/cjs/auth/credential_service/base_credential_service.js +1 -1
  39. package/dist/cjs/auth/credential_service/in_memory_credential_service.js +1 -1
  40. package/dist/cjs/auth/exchanger/base_credential_exchanger.js +1 -1
  41. package/dist/cjs/auth/exchanger/credential_exchanger_registry.js +1 -1
  42. package/dist/cjs/code_executors/base_code_executor.js +1 -1
  43. package/dist/cjs/code_executors/built_in_code_executor.js +1 -1
  44. package/dist/cjs/code_executors/code_execution_utils.js +1 -1
  45. package/dist/cjs/code_executors/code_executor_context.js +1 -1
  46. package/dist/cjs/common.js +25 -8
  47. package/dist/cjs/events/event.js +33 -4
  48. package/dist/cjs/events/event_actions.js +2 -2
  49. package/dist/cjs/events/structured_events.js +105 -0
  50. package/dist/cjs/examples/base_example_provider.js +1 -1
  51. package/dist/cjs/examples/example.js +1 -1
  52. package/dist/cjs/examples/example_util.js +1 -1
  53. package/dist/cjs/index.js +24 -17
  54. package/dist/cjs/index.js.map +4 -4
  55. package/dist/cjs/index_web.js +1 -1
  56. package/dist/cjs/memory/base_memory_service.js +1 -1
  57. package/dist/cjs/memory/in_memory_memory_service.js +1 -1
  58. package/dist/cjs/memory/memory_entry.js +1 -1
  59. package/dist/cjs/models/apigee_llm.js +182 -0
  60. package/dist/cjs/models/base_llm.js +1 -1
  61. package/dist/cjs/models/base_llm_connection.js +1 -1
  62. package/dist/cjs/models/gemini_llm_connection.js +1 -1
  63. package/dist/cjs/models/google_llm.js +70 -51
  64. package/dist/cjs/models/llm_request.js +1 -1
  65. package/dist/cjs/models/llm_response.js +3 -1
  66. package/dist/cjs/models/registry.js +3 -1
  67. package/dist/cjs/plugins/base_plugin.js +2 -2
  68. package/dist/cjs/plugins/logging_plugin.js +1 -1
  69. package/dist/cjs/plugins/plugin_manager.js +1 -1
  70. package/dist/cjs/plugins/security_plugin.js +1 -1
  71. package/dist/cjs/runner/in_memory_runner.js +1 -1
  72. package/dist/cjs/runner/runner.js +33 -2
  73. package/dist/cjs/sessions/base_session_service.js +53 -3
  74. package/dist/cjs/sessions/database_session_service.js +367 -0
  75. package/dist/cjs/sessions/db/operations.js +126 -0
  76. package/dist/cjs/sessions/db/schema.js +204 -0
  77. package/dist/cjs/sessions/in_memory_session_service.js +24 -22
  78. package/dist/cjs/sessions/registry.js +49 -0
  79. package/dist/cjs/sessions/session.js +1 -1
  80. package/dist/cjs/sessions/state.js +1 -1
  81. package/dist/cjs/telemetry/google_cloud.js +1 -1
  82. package/dist/cjs/telemetry/setup.js +1 -1
  83. package/dist/cjs/telemetry/tracing.js +1 -1
  84. package/dist/cjs/tools/agent_tool.js +1 -1
  85. package/dist/cjs/tools/base_tool.js +4 -1
  86. package/dist/cjs/tools/base_toolset.js +14 -4
  87. package/dist/cjs/tools/exit_loop_tool.js +63 -0
  88. package/dist/cjs/tools/forwarding_artifact_service.js +17 -1
  89. package/dist/cjs/tools/function_tool.js +1 -1
  90. package/dist/cjs/tools/google_search_tool.js +1 -1
  91. package/dist/cjs/tools/long_running_tool.js +1 -1
  92. package/dist/cjs/tools/mcp/mcp_session_manager.js +1 -1
  93. package/dist/cjs/tools/mcp/mcp_tool.js +1 -1
  94. package/dist/cjs/tools/mcp/mcp_toolset.js +10 -6
  95. package/dist/cjs/tools/tool_confirmation.js +1 -1
  96. package/dist/cjs/utils/client_labels.js +1 -1
  97. package/dist/cjs/utils/env_aware_utils.js +10 -1
  98. package/dist/cjs/utils/gemini_schema_util.js +1 -1
  99. package/dist/cjs/utils/logger.js +62 -55
  100. package/dist/cjs/utils/model_name.js +1 -1
  101. package/dist/cjs/utils/object_notation_utils.js +78 -0
  102. package/dist/cjs/utils/simple_zod_to_json.js +1 -1
  103. package/dist/cjs/utils/variant_utils.js +3 -9
  104. package/dist/cjs/version.js +2 -2
  105. package/dist/esm/a2a/a2a_event.js +243 -0
  106. package/dist/esm/a2a/event_converter_utils.js +187 -0
  107. package/dist/esm/a2a/executor_context.js +23 -0
  108. package/dist/esm/a2a/metadata_converter_utils.js +90 -0
  109. package/dist/esm/a2a/part_converter_utils.js +175 -0
  110. package/dist/esm/agents/base_agent.js +5 -5
  111. package/dist/esm/{tools/tool_context.js → agents/context.js} +66 -11
  112. package/dist/esm/agents/functions.js +3 -2
  113. package/dist/esm/agents/llm_agent.js +69 -720
  114. package/dist/esm/agents/processors/agent_transfer_llm_request_processor.js +101 -0
  115. package/dist/esm/agents/processors/basic_llm_request_processor.js +37 -0
  116. package/dist/esm/agents/processors/code_execution_request_processor.js +363 -0
  117. package/dist/esm/agents/processors/content_request_processor.js +38 -0
  118. package/dist/esm/agents/processors/identity_llm_request_processor.js +23 -0
  119. package/dist/esm/agents/processors/instructions_llm_request_processor.js +54 -0
  120. package/dist/esm/agents/processors/request_confirmation_llm_request_processor.js +140 -0
  121. package/dist/esm/agents/readonly_context.js +12 -0
  122. package/dist/esm/agents/run_config.js +1 -0
  123. package/dist/esm/artifacts/file_artifact_service.js +451 -0
  124. package/dist/esm/artifacts/gcs_artifact_service.js +126 -47
  125. package/dist/esm/artifacts/in_memory_artifact_service.js +51 -4
  126. package/dist/esm/artifacts/registry.js +28 -0
  127. package/dist/esm/common.js +20 -10
  128. package/dist/esm/events/event.js +29 -2
  129. package/dist/esm/events/event_actions.js +1 -1
  130. package/dist/esm/events/structured_events.js +74 -0
  131. package/dist/esm/index.js +24 -17
  132. package/dist/esm/index.js.map +4 -4
  133. package/dist/esm/models/apigee_llm.js +152 -0
  134. package/dist/esm/models/google_llm.js +67 -49
  135. package/dist/esm/models/llm_response.js +2 -0
  136. package/dist/esm/models/registry.js +2 -0
  137. package/dist/esm/plugins/base_plugin.js +1 -1
  138. package/dist/esm/runner/runner.js +32 -1
  139. package/dist/esm/sessions/base_session_service.js +49 -1
  140. package/dist/esm/sessions/database_session_service.js +353 -0
  141. package/dist/esm/sessions/db/operations.js +111 -0
  142. package/dist/esm/sessions/db/schema.js +172 -0
  143. package/dist/esm/sessions/in_memory_session_service.js +23 -21
  144. package/dist/esm/sessions/registry.js +25 -0
  145. package/dist/esm/tools/base_tool.js +3 -0
  146. package/dist/esm/tools/base_toolset.js +11 -2
  147. package/dist/esm/tools/exit_loop_tool.js +32 -0
  148. package/dist/esm/tools/forwarding_artifact_service.js +16 -0
  149. package/dist/esm/tools/mcp/mcp_toolset.js +9 -5
  150. package/dist/esm/utils/env_aware_utils.js +8 -0
  151. package/dist/esm/utils/logger.js +51 -54
  152. package/dist/esm/utils/object_notation_utils.js +47 -0
  153. package/dist/esm/utils/variant_utils.js +1 -7
  154. package/dist/esm/version.js +1 -1
  155. package/dist/types/a2a/a2a_event.d.ts +122 -0
  156. package/dist/types/a2a/event_converter_utils.d.ts +20 -0
  157. package/dist/types/a2a/executor_context.d.ts +33 -0
  158. package/dist/types/a2a/metadata_converter_utils.d.ts +62 -0
  159. package/dist/types/a2a/part_converter_utils.d.ts +48 -0
  160. package/dist/types/agents/base_agent.d.ts +2 -2
  161. package/dist/types/{tools/tool_context.d.ts → agents/context.d.ts} +43 -8
  162. package/dist/types/agents/llm_agent.d.ts +19 -42
  163. package/dist/types/agents/processors/agent_transfer_llm_request_processor.d.ts +18 -0
  164. package/dist/types/agents/{base_llm_processor.d.ts → processors/base_llm_processor.d.ts} +4 -4
  165. package/dist/types/agents/processors/basic_llm_request_processor.d.ts +13 -0
  166. package/dist/types/agents/processors/code_execution_request_processor.d.ts +34 -0
  167. package/dist/types/agents/processors/content_request_processor.d.ts +13 -0
  168. package/dist/types/agents/processors/identity_llm_request_processor.d.ts +13 -0
  169. package/dist/types/agents/processors/instructions_llm_request_processor.d.ts +16 -0
  170. package/dist/types/agents/processors/request_confirmation_llm_request_processor.d.ts +13 -0
  171. package/dist/types/agents/readonly_context.d.ts +8 -0
  172. package/dist/types/agents/run_config.d.ts +6 -0
  173. package/dist/types/artifacts/base_artifact_service.d.ts +31 -0
  174. package/dist/types/artifacts/file_artifact_service.d.ts +43 -0
  175. package/dist/types/artifacts/gcs_artifact_service.d.ts +3 -1
  176. package/dist/types/artifacts/in_memory_artifact_service.d.ts +5 -2
  177. package/dist/types/artifacts/registry.d.ts +7 -0
  178. package/dist/types/auth/credential_service/base_credential_service.d.ts +3 -3
  179. package/dist/types/auth/credential_service/in_memory_credential_service.d.ts +3 -3
  180. package/dist/types/common.d.ts +15 -6
  181. package/dist/types/events/event.d.ts +15 -1
  182. package/dist/types/events/event_actions.d.ts +1 -1
  183. package/dist/types/events/structured_events.d.ts +106 -0
  184. package/dist/types/index.d.ts +5 -1
  185. package/dist/types/models/apigee_llm.d.ts +59 -0
  186. package/dist/types/models/google_llm.d.ts +5 -2
  187. package/dist/types/models/llm_response.d.ts +5 -1
  188. package/dist/types/plugins/base_plugin.d.ts +12 -13
  189. package/dist/types/plugins/logging_plugin.d.ts +9 -10
  190. package/dist/types/plugins/plugin_manager.d.ts +9 -10
  191. package/dist/types/plugins/security_plugin.d.ts +2 -2
  192. package/dist/types/runner/runner.d.ts +15 -0
  193. package/dist/types/sessions/base_session_service.d.ts +20 -0
  194. package/dist/types/sessions/database_session_service.d.ts +32 -0
  195. package/dist/types/sessions/db/operations.d.ts +29 -0
  196. package/dist/types/sessions/db/schema.d.ts +45 -0
  197. package/dist/types/sessions/in_memory_session_service.d.ts +4 -1
  198. package/dist/types/sessions/registry.d.ts +7 -0
  199. package/dist/types/tools/base_tool.d.ts +3 -3
  200. package/dist/types/tools/base_toolset.d.ts +12 -3
  201. package/dist/types/tools/exit_loop_tool.d.ts +24 -0
  202. package/dist/types/tools/forwarding_artifact_service.d.ts +5 -3
  203. package/dist/types/tools/function_tool.d.ts +2 -2
  204. package/dist/types/tools/mcp/mcp_toolset.d.ts +1 -1
  205. package/dist/types/utils/env_aware_utils.d.ts +7 -0
  206. package/dist/types/utils/logger.d.ts +5 -9
  207. package/dist/types/utils/object_notation_utils.d.ts +21 -0
  208. package/dist/types/version.d.ts +1 -1
  209. package/dist/web/a2a/a2a_event.js +243 -0
  210. package/dist/web/a2a/event_converter_utils.js +201 -0
  211. package/dist/web/a2a/executor_context.js +23 -0
  212. package/dist/web/a2a/metadata_converter_utils.js +107 -0
  213. package/dist/web/a2a/part_converter_utils.js +175 -0
  214. package/dist/web/agents/base_agent.js +5 -5
  215. package/dist/web/{tools/tool_context.js → agents/context.js} +66 -11
  216. package/dist/web/agents/functions.js +3 -2
  217. package/dist/web/agents/llm_agent.js +90 -717
  218. package/dist/web/agents/processors/agent_transfer_llm_request_processor.js +100 -0
  219. package/dist/web/agents/processors/basic_llm_request_processor.js +71 -0
  220. package/dist/web/agents/processors/code_execution_request_processor.js +365 -0
  221. package/dist/web/agents/processors/content_request_processor.js +56 -0
  222. package/dist/web/agents/processors/identity_llm_request_processor.js +41 -0
  223. package/dist/web/agents/processors/instructions_llm_request_processor.js +72 -0
  224. package/dist/web/agents/processors/request_confirmation_llm_request_processor.js +158 -0
  225. package/dist/web/agents/readonly_context.js +12 -0
  226. package/dist/web/agents/run_config.js +2 -1
  227. package/dist/web/artifacts/file_artifact_service.js +506 -0
  228. package/dist/web/artifacts/gcs_artifact_service.js +123 -46
  229. package/dist/web/artifacts/in_memory_artifact_service.js +51 -4
  230. package/dist/web/artifacts/registry.js +28 -0
  231. package/dist/web/common.js +20 -10
  232. package/dist/web/events/event.js +29 -2
  233. package/dist/web/events/event_actions.js +1 -1
  234. package/dist/web/events/structured_events.js +74 -0
  235. package/dist/web/index.js +7 -2
  236. package/dist/web/index.js.map +4 -4
  237. package/dist/web/models/apigee_llm.js +219 -0
  238. package/dist/web/models/google_llm.js +67 -46
  239. package/dist/web/models/llm_response.js +2 -0
  240. package/dist/web/models/registry.js +2 -0
  241. package/dist/web/plugins/base_plugin.js +1 -1
  242. package/dist/web/runner/runner.js +34 -1
  243. package/dist/web/sessions/base_session_service.js +49 -1
  244. package/dist/web/sessions/database_session_service.js +371 -0
  245. package/dist/web/sessions/db/operations.js +111 -0
  246. package/dist/web/sessions/db/schema.js +172 -0
  247. package/dist/web/sessions/in_memory_session_service.js +23 -21
  248. package/dist/web/sessions/registry.js +25 -0
  249. package/dist/web/tools/base_tool.js +3 -0
  250. package/dist/web/tools/base_toolset.js +11 -2
  251. package/dist/web/tools/exit_loop_tool.js +32 -0
  252. package/dist/web/tools/forwarding_artifact_service.js +16 -0
  253. package/dist/web/tools/mcp/mcp_toolset.js +27 -5
  254. package/dist/web/utils/env_aware_utils.js +8 -0
  255. package/dist/web/utils/logger.js +51 -54
  256. package/dist/web/utils/object_notation_utils.js +47 -0
  257. package/dist/web/utils/variant_utils.js +1 -7
  258. package/dist/web/version.js +1 -1
  259. package/package.json +13 -3
  260. package/dist/cjs/agents/callback_context.js +0 -101
  261. package/dist/esm/agents/callback_context.js +0 -71
  262. package/dist/types/agents/callback_context.d.ts +0 -42
  263. package/dist/web/agents/callback_context.js +0 -71
  264. /package/dist/esm/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
  265. /package/dist/web/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
@@ -69,691 +69,47 @@ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")])
69
69
  */
70
70
  var _a, _b;
71
71
  import { context, trace } from "@opentelemetry/api";
72
- import { cloneDeep } from "lodash-es";
73
- import { z } from "zod";
74
- import {
75
- isBaseCodeExecutor
76
- } from "../code_executors/base_code_executor.js";
77
- import { isBuiltInCodeExecutor } from "../code_executors/built_in_code_executor.js";
78
- import {
79
- buildCodeExecutionResultPart,
80
- buildExecutableCodePart,
81
- convertCodeExecutionParts,
82
- extractCodeAndTruncateContent
83
- } from "../code_executors/code_execution_utils.js";
84
- import { CodeExecutorContext } from "../code_executors/code_executor_context.js";
85
72
  import {
86
73
  createEvent,
87
74
  createNewEventId,
88
75
  getFunctionCalls,
89
- getFunctionResponses,
90
76
  isFinalResponse
91
77
  } from "../events/event.js";
92
- import { createEventActions } from "../events/event_actions.js";
93
78
  import { isBaseLlm } from "../models/base_llm.js";
94
- import {
95
- appendInstructions,
96
- setOutputSchema
97
- } from "../models/llm_request.js";
98
79
  import { LLMRegistry } from "../models/registry.js";
99
- import { State } from "../sessions/state.js";
100
- import { BaseTool } from "../tools/base_tool.js";
101
- import { FunctionTool } from "../tools/function_tool.js";
102
- import { ToolConfirmation } from "../tools/tool_confirmation.js";
103
- import { ToolContext } from "../tools/tool_context.js";
104
- import { base64Decode } from "../utils/env_aware_utils.js";
80
+ import { isBaseTool } from "../tools/base_tool.js";
105
81
  import { logger } from "../utils/logger.js";
82
+ import { Context } from "./context.js";
106
83
  import {
107
84
  runAsyncGeneratorWithOtelContext,
108
85
  traceCallLlm,
109
86
  tracer
110
87
  } from "../telemetry/tracing.js";
88
+ import { isZodObject, zodObjectToSchema } from "../utils/simple_zod_to_json.js";
111
89
  import { BaseAgent } from "./base_agent.js";
112
- import {
113
- BaseLlmRequestProcessor
114
- } from "./base_llm_processor.js";
115
- import { CallbackContext } from "./callback_context.js";
116
- import {
117
- getContents,
118
- getCurrentTurnContents
119
- } from "./content_processor_utils.js";
120
90
  import {
121
91
  generateAuthEvent,
122
92
  generateRequestConfirmationEvent,
123
93
  getLongRunningFunctionCalls,
124
- handleFunctionCallList,
125
94
  handleFunctionCallsAsync,
126
- populateClientFunctionCallId,
127
- REQUEST_CONFIRMATION_FUNCTION_CALL_NAME
95
+ populateClientFunctionCallId
128
96
  } from "./functions.js";
129
- import { injectSessionState } from "./instructions.js";
97
+ import { AGENT_TRANSFER_LLM_REQUEST_PROCESSOR } from "./processors/agent_transfer_llm_request_processor.js";
98
+ import { BASIC_LLM_REQUEST_PROCESSOR } from "./processors/basic_llm_request_processor.js";
99
+ import { CODE_EXECUTION_REQUEST_PROCESSOR } from "./processors/code_execution_request_processor.js";
100
+ import { CONTENT_REQUEST_PROCESSOR } from "./processors/content_request_processor.js";
101
+ import { IDENTITY_LLM_REQUEST_PROCESSOR } from "./processors/identity_llm_request_processor.js";
102
+ import { INSTRUCTIONS_LLM_REQUEST_PROCESSOR } from "./processors/instructions_llm_request_processor.js";
103
+ import { REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR } from "./processors/request_confirmation_llm_request_processor.js";
130
104
  import { ReadonlyContext } from "./readonly_context.js";
131
105
  import { StreamingMode } from "./run_config.js";
132
106
  const ADK_AGENT_NAME_LABEL_KEY = "adk_agent_name";
133
107
  async function convertToolUnionToTools(toolUnion, context2) {
134
- if (toolUnion instanceof BaseTool) {
108
+ if (isBaseTool(toolUnion)) {
135
109
  return [toolUnion];
136
110
  }
137
111
  return await toolUnion.getTools(context2);
138
112
  }
139
- class BasicLlmRequestProcessor extends BaseLlmRequestProcessor {
140
- // eslint-disable-next-line require-yield
141
- runAsync(invocationContext, llmRequest) {
142
- return __asyncGenerator(this, null, function* () {
143
- var _a2;
144
- const agent = invocationContext.agent;
145
- if (!isLlmAgent(agent)) {
146
- return;
147
- }
148
- llmRequest.model = agent.canonicalModel.model;
149
- llmRequest.config = __spreadValues({}, (_a2 = agent.generateContentConfig) != null ? _a2 : {});
150
- if (agent.outputSchema) {
151
- setOutputSchema(llmRequest, agent.outputSchema);
152
- }
153
- if (invocationContext.runConfig) {
154
- llmRequest.liveConnectConfig.responseModalities = invocationContext.runConfig.responseModalities;
155
- llmRequest.liveConnectConfig.speechConfig = invocationContext.runConfig.speechConfig;
156
- llmRequest.liveConnectConfig.outputAudioTranscription = invocationContext.runConfig.outputAudioTranscription;
157
- llmRequest.liveConnectConfig.inputAudioTranscription = invocationContext.runConfig.inputAudioTranscription;
158
- llmRequest.liveConnectConfig.realtimeInputConfig = invocationContext.runConfig.realtimeInputConfig;
159
- llmRequest.liveConnectConfig.enableAffectiveDialog = invocationContext.runConfig.enableAffectiveDialog;
160
- llmRequest.liveConnectConfig.proactivity = invocationContext.runConfig.proactivity;
161
- }
162
- });
163
- }
164
- }
165
- const BASIC_LLM_REQUEST_PROCESSOR = new BasicLlmRequestProcessor();
166
- class IdentityLlmRequestProcessor extends BaseLlmRequestProcessor {
167
- // eslint-disable-next-line require-yield
168
- runAsync(invocationContext, llmRequest) {
169
- return __asyncGenerator(this, null, function* () {
170
- const agent = invocationContext.agent;
171
- const si = ['You are an agent. Your internal name is "'.concat(agent.name, '".')];
172
- if (agent.description) {
173
- si.push('The description about you is "'.concat(agent.description, '"'));
174
- }
175
- appendInstructions(llmRequest, si);
176
- });
177
- }
178
- }
179
- const IDENTITY_LLM_REQUEST_PROCESSOR = new IdentityLlmRequestProcessor();
180
- class InstructionsLlmRequestProcessor extends BaseLlmRequestProcessor {
181
- /**
182
- * Handles instructions and global instructions for LLM flow.
183
- */
184
- // eslint-disable-next-line require-yield
185
- runAsync(invocationContext, llmRequest) {
186
- return __asyncGenerator(this, null, function* () {
187
- const agent = invocationContext.agent;
188
- if (!(agent instanceof LlmAgent) || !(agent.rootAgent instanceof LlmAgent)) {
189
- return;
190
- }
191
- const rootAgent = agent.rootAgent;
192
- if (isLlmAgent(rootAgent) && rootAgent.globalInstruction) {
193
- const { instruction, requireStateInjection } = yield new __await(rootAgent.canonicalGlobalInstruction(
194
- new ReadonlyContext(invocationContext)
195
- ));
196
- let instructionWithState = instruction;
197
- if (requireStateInjection) {
198
- instructionWithState = yield new __await(injectSessionState(
199
- instruction,
200
- new ReadonlyContext(invocationContext)
201
- ));
202
- }
203
- appendInstructions(llmRequest, [instructionWithState]);
204
- }
205
- if (agent.instruction) {
206
- const { instruction, requireStateInjection } = yield new __await(agent.canonicalInstruction(
207
- new ReadonlyContext(invocationContext)
208
- ));
209
- let instructionWithState = instruction;
210
- if (requireStateInjection) {
211
- instructionWithState = yield new __await(injectSessionState(
212
- instruction,
213
- new ReadonlyContext(invocationContext)
214
- ));
215
- }
216
- appendInstructions(llmRequest, [instructionWithState]);
217
- }
218
- });
219
- }
220
- }
221
- const INSTRUCTIONS_LLM_REQUEST_PROCESSOR = new InstructionsLlmRequestProcessor();
222
- class ContentRequestProcessor {
223
- // eslint-disable-next-line require-yield
224
- runAsync(invocationContext, llmRequest) {
225
- return __asyncGenerator(this, null, function* () {
226
- const agent = invocationContext.agent;
227
- if (!agent || !isLlmAgent(agent)) {
228
- return;
229
- }
230
- if (agent.includeContents === "default") {
231
- llmRequest.contents = getContents(
232
- invocationContext.session.events,
233
- agent.name,
234
- invocationContext.branch
235
- );
236
- } else {
237
- llmRequest.contents = getCurrentTurnContents(
238
- invocationContext.session.events,
239
- agent.name,
240
- invocationContext.branch
241
- );
242
- }
243
- return;
244
- });
245
- }
246
- }
247
- const CONTENT_REQUEST_PROCESSOR = new ContentRequestProcessor();
248
- class AgentTransferLlmRequestProcessor extends BaseLlmRequestProcessor {
249
- constructor() {
250
- super(...arguments);
251
- this.toolName = "transfer_to_agent";
252
- this.tool = new FunctionTool({
253
- name: this.toolName,
254
- 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.",
255
- parameters: z.object({
256
- agentName: z.string().describe("the agent name to transfer to.")
257
- }),
258
- execute: function(args, toolContext) {
259
- if (!toolContext) {
260
- throw new Error("toolContext is required.");
261
- }
262
- toolContext.actions.transferToAgent = args.agentName;
263
- return "Transfer queued";
264
- }
265
- });
266
- }
267
- // eslint-disable-next-line require-yield
268
- runAsync(invocationContext, llmRequest) {
269
- return __asyncGenerator(this, null, function* () {
270
- if (!(invocationContext.agent instanceof LlmAgent)) {
271
- return;
272
- }
273
- const transferTargets = this.getTransferTargets(invocationContext.agent);
274
- if (!transferTargets.length) {
275
- return;
276
- }
277
- appendInstructions(llmRequest, [
278
- this.buildTargetAgentsInstructions(
279
- invocationContext.agent,
280
- transferTargets
281
- )
282
- ]);
283
- const toolContext = new ToolContext({ invocationContext });
284
- yield new __await(this.tool.processLlmRequest({ toolContext, llmRequest }));
285
- });
286
- }
287
- buildTargetAgentsInfo(targetAgent) {
288
- return "\nAgent name: ".concat(targetAgent.name, "\nAgent description: ").concat(targetAgent.description, "\n");
289
- }
290
- buildTargetAgentsInstructions(agent, targetAgents) {
291
- 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");
292
- if (agent.parentAgent && !agent.disallowTransferToParent) {
293
- 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");
294
- }
295
- return instructions;
296
- }
297
- getTransferTargets(agent) {
298
- const targets = [];
299
- targets.push(...agent.subAgents);
300
- if (!agent.parentAgent || !isLlmAgent(agent.parentAgent)) {
301
- return targets;
302
- }
303
- if (!agent.disallowTransferToParent) {
304
- targets.push(agent.parentAgent);
305
- }
306
- if (!agent.disallowTransferToPeers) {
307
- targets.push(
308
- ...agent.parentAgent.subAgents.filter(
309
- (peerAgent) => peerAgent.name !== agent.name
310
- )
311
- );
312
- }
313
- return targets;
314
- }
315
- }
316
- const AGENT_TRANSFER_LLM_REQUEST_PROCESSOR = new AgentTransferLlmRequestProcessor();
317
- class RequestConfirmationLlmRequestProcessor extends BaseLlmRequestProcessor {
318
- /** Handles tool confirmation information to build the LLM request. */
319
- runAsync(invocationContext) {
320
- return __asyncGenerator(this, null, function* () {
321
- const agent = invocationContext.agent;
322
- if (!isLlmAgent(agent)) {
323
- return;
324
- }
325
- const events = invocationContext.session.events;
326
- if (!events || events.length === 0) {
327
- return;
328
- }
329
- const requestConfirmationFunctionResponses = {};
330
- let confirmationEventIndex = -1;
331
- for (let i = events.length - 1; i >= 0; i--) {
332
- const event = events[i];
333
- if (event.author !== "user") {
334
- continue;
335
- }
336
- const responses = getFunctionResponses(event);
337
- if (!responses) {
338
- continue;
339
- }
340
- let foundConfirmation = false;
341
- for (const functionResponse of responses) {
342
- if (functionResponse.name !== REQUEST_CONFIRMATION_FUNCTION_CALL_NAME) {
343
- continue;
344
- }
345
- foundConfirmation = true;
346
- let toolConfirmation = null;
347
- if (functionResponse.response && Object.keys(functionResponse.response).length === 1 && "response" in functionResponse.response) {
348
- toolConfirmation = JSON.parse(
349
- functionResponse.response["response"]
350
- );
351
- } else if (functionResponse.response) {
352
- toolConfirmation = new ToolConfirmation({
353
- hint: functionResponse.response["hint"],
354
- payload: functionResponse.response["payload"],
355
- confirmed: functionResponse.response["confirmed"]
356
- });
357
- }
358
- if (functionResponse.id && toolConfirmation) {
359
- requestConfirmationFunctionResponses[functionResponse.id] = toolConfirmation;
360
- }
361
- }
362
- if (foundConfirmation) {
363
- confirmationEventIndex = i;
364
- break;
365
- }
366
- }
367
- if (Object.keys(requestConfirmationFunctionResponses).length === 0) {
368
- return;
369
- }
370
- for (let i = confirmationEventIndex - 1; i >= 0; i--) {
371
- const event = events[i];
372
- const functionCalls = getFunctionCalls(event);
373
- if (!functionCalls) {
374
- continue;
375
- }
376
- const toolsToResumeWithConfirmation = {};
377
- const toolsToResumeWithArgs = {};
378
- for (const functionCall of functionCalls) {
379
- if (!functionCall.id || !(functionCall.id in requestConfirmationFunctionResponses)) {
380
- continue;
381
- }
382
- const args = functionCall.args;
383
- if (!args || !("originalFunctionCall" in args)) {
384
- continue;
385
- }
386
- const originalFunctionCall = args["originalFunctionCall"];
387
- if (originalFunctionCall.id) {
388
- toolsToResumeWithConfirmation[originalFunctionCall.id] = requestConfirmationFunctionResponses[functionCall.id];
389
- toolsToResumeWithArgs[originalFunctionCall.id] = originalFunctionCall;
390
- }
391
- }
392
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
393
- continue;
394
- }
395
- for (let j = events.length - 1; j > confirmationEventIndex; j--) {
396
- const eventToCheck = events[j];
397
- const functionResponses = getFunctionResponses(eventToCheck);
398
- if (!functionResponses) {
399
- continue;
400
- }
401
- for (const fr of functionResponses) {
402
- if (fr.id && fr.id in toolsToResumeWithConfirmation) {
403
- delete toolsToResumeWithConfirmation[fr.id];
404
- delete toolsToResumeWithArgs[fr.id];
405
- }
406
- }
407
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
408
- break;
409
- }
410
- }
411
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
412
- continue;
413
- }
414
- const toolsList = yield new __await(agent.canonicalTools(
415
- new ReadonlyContext(invocationContext)
416
- ));
417
- const toolsDict = Object.fromEntries(
418
- toolsList.map((tool) => [tool.name, tool])
419
- );
420
- const functionResponseEvent = yield new __await(handleFunctionCallList({
421
- invocationContext,
422
- functionCalls: Object.values(toolsToResumeWithArgs),
423
- toolsDict,
424
- beforeToolCallbacks: agent.canonicalBeforeToolCallbacks,
425
- afterToolCallbacks: agent.canonicalAfterToolCallbacks,
426
- filters: new Set(Object.keys(toolsToResumeWithConfirmation)),
427
- toolConfirmationDict: toolsToResumeWithConfirmation
428
- }));
429
- if (functionResponseEvent) {
430
- yield functionResponseEvent;
431
- }
432
- return;
433
- }
434
- });
435
- }
436
- }
437
- const REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR = new RequestConfirmationLlmRequestProcessor();
438
- class CodeExecutionRequestProcessor extends BaseLlmRequestProcessor {
439
- runAsync(invocationContext, llmRequest) {
440
- return __asyncGenerator(this, null, function* () {
441
- if (!(invocationContext.agent instanceof LlmAgent)) {
442
- return;
443
- }
444
- if (!invocationContext.agent.codeExecutor) {
445
- return;
446
- }
447
- try {
448
- for (var iter = __forAwait(runPreProcessor(invocationContext, llmRequest)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
449
- const event = temp.value;
450
- yield event;
451
- }
452
- } catch (temp) {
453
- error = [temp];
454
- } finally {
455
- try {
456
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
457
- } finally {
458
- if (error)
459
- throw error[0];
460
- }
461
- }
462
- if (!isBaseCodeExecutor(invocationContext.agent.codeExecutor)) {
463
- return;
464
- }
465
- for (const content of llmRequest.contents) {
466
- const delimeters = invocationContext.agent.codeExecutor.codeBlockDelimiters.length ? invocationContext.agent.codeExecutor.codeBlockDelimiters[0] : ["", ""];
467
- convertCodeExecutionParts(
468
- content,
469
- delimeters,
470
- invocationContext.agent.codeExecutor.executionResultDelimiters
471
- );
472
- }
473
- });
474
- }
475
- }
476
- const DATA_FILE_UTIL_MAP = {
477
- "text/csv": {
478
- extension: ".csv",
479
- loaderCodeTemplate: "pd.read_csv('{filename}')"
480
- }
481
- };
482
- const DATA_FILE_HELPER_LIB = "\nimport pandas as pd\n\ndef explore_df(df: pd.DataFrame) -> None:\n \"\"\"Prints some information about a pandas DataFrame.\"\"\"\n\n with pd.option_context(\n 'display.max_columns', None, 'display.expand_frame_repr', False\n ):\n # Print the column names to never encounter KeyError when selecting one.\n df_dtypes = df.dtypes\n\n # Obtain information about data types and missing values.\n df_nulls = (len(df) - df.isnull().sum()).apply(\n lambda x: f'{x} / {df.shape[0]} non-null'\n )\n\n # Explore unique total values in columns using `.unique()`.\n df_unique_count = df.apply(lambda x: len(x.unique()))\n\n # Explore unique values in columns using `.unique()`.\n df_unique = df.apply(lambda x: crop(str(list(x.unique()))))\n\n df_info = pd.concat(\n (\n df_dtypes.rename('Dtype'),\n df_nulls.rename('Non-Null Count'),\n df_unique_count.rename('Unique Values Count'),\n df_unique.rename('Unique Values'),\n ),\n axis=1,\n )\n df_info.index.name = 'Columns'\n print(f\"\"\"Total rows: {df.shape[0]}\nTotal columns: {df.shape[1]}\n\n{df_info}\"\"\")\n";
483
- class CodeExecutionResponseProcessor {
484
- /**
485
- * Processes the LLM response asynchronously.
486
- *
487
- * @param invocationContext The invocation context
488
- * @param llmResponse The LLM response to process
489
- * @returns An async generator yielding events
490
- */
491
- runAsync(invocationContext, llmResponse) {
492
- return __asyncGenerator(this, null, function* () {
493
- if (llmResponse.partial) {
494
- return;
495
- }
496
- try {
497
- for (var iter = __forAwait(runPostProcessor(
498
- invocationContext,
499
- llmResponse
500
- )), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
501
- const event = temp.value;
502
- yield event;
503
- }
504
- } catch (temp) {
505
- error = [temp];
506
- } finally {
507
- try {
508
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
509
- } finally {
510
- if (error)
511
- throw error[0];
512
- }
513
- }
514
- });
515
- }
516
- }
517
- const responseProcessor = new CodeExecutionResponseProcessor();
518
- function runPreProcessor(invocationContext, llmRequest) {
519
- return __asyncGenerator(this, null, function* () {
520
- const agent = invocationContext.agent;
521
- if (!isLlmAgent(agent)) {
522
- return;
523
- }
524
- const codeExecutor = agent.codeExecutor;
525
- if (!codeExecutor || !isBaseCodeExecutor(codeExecutor)) {
526
- return;
527
- }
528
- if (isBuiltInCodeExecutor(codeExecutor)) {
529
- codeExecutor.processLlmRequest(llmRequest);
530
- return;
531
- }
532
- if (!codeExecutor.optimizeDataFile) {
533
- return;
534
- }
535
- const codeExecutorContext = new CodeExecutorContext(
536
- new State(invocationContext.session.state)
537
- );
538
- if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
539
- return;
540
- }
541
- const allInputFiles = extractAndReplaceInlineFiles(
542
- codeExecutorContext,
543
- llmRequest
544
- );
545
- const processedFileNames = new Set(
546
- codeExecutorContext.getProcessedFileNames()
547
- );
548
- const filesToProcess = allInputFiles.filter(
549
- (f) => !processedFileNames.has(f.name)
550
- );
551
- for (const file of filesToProcess) {
552
- const codeStr = getDataFilePreprocessingCode(file);
553
- if (!codeStr) {
554
- return;
555
- }
556
- const codeContent = {
557
- role: "model",
558
- parts: [
559
- { text: "Processing input file: `".concat(file.name, "`") },
560
- buildExecutableCodePart(codeStr)
561
- ]
562
- };
563
- llmRequest.contents.push(cloneDeep(codeContent));
564
- yield createEvent({
565
- invocationId: invocationContext.invocationId,
566
- author: agent.name,
567
- branch: invocationContext.branch,
568
- content: codeContent
569
- });
570
- const executionId = getOrSetExecutionId(
571
- invocationContext,
572
- codeExecutorContext
573
- );
574
- const codeExecutionResult = yield new __await(codeExecutor.executeCode({
575
- invocationContext,
576
- codeExecutionInput: {
577
- code: codeStr,
578
- inputFiles: [file],
579
- executionId
580
- }
581
- }));
582
- codeExecutorContext.updateCodeExecutionResult({
583
- invocationId: invocationContext.invocationId,
584
- code: codeStr,
585
- resultStdout: codeExecutionResult.stdout,
586
- resultStderr: codeExecutionResult.stderr
587
- });
588
- codeExecutorContext.addProcessedFileNames([file.name]);
589
- const executionResultEvent = yield new __await(postProcessCodeExecutionResult(
590
- invocationContext,
591
- codeExecutorContext,
592
- codeExecutionResult
593
- ));
594
- yield executionResultEvent;
595
- llmRequest.contents.push(cloneDeep(executionResultEvent.content));
596
- }
597
- });
598
- }
599
- function runPostProcessor(invocationContext, llmResponse) {
600
- return __asyncGenerator(this, null, function* () {
601
- const agent = invocationContext.agent;
602
- if (!isLlmAgent(agent)) {
603
- return;
604
- }
605
- const codeExecutor = agent.codeExecutor;
606
- if (!codeExecutor || !isBaseCodeExecutor(codeExecutor)) {
607
- return;
608
- }
609
- if (!llmResponse || !llmResponse.content) {
610
- return;
611
- }
612
- if (isBuiltInCodeExecutor(codeExecutor)) {
613
- return;
614
- }
615
- const codeExecutorContext = new CodeExecutorContext(
616
- new State(invocationContext.session.state)
617
- );
618
- if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
619
- return;
620
- }
621
- const responseContent = llmResponse.content;
622
- const codeStr = extractCodeAndTruncateContent(
623
- responseContent,
624
- codeExecutor.codeBlockDelimiters
625
- );
626
- if (!codeStr) {
627
- return;
628
- }
629
- yield createEvent({
630
- invocationId: invocationContext.invocationId,
631
- author: agent.name,
632
- branch: invocationContext.branch,
633
- content: responseContent
634
- });
635
- const executionId = getOrSetExecutionId(
636
- invocationContext,
637
- codeExecutorContext
638
- );
639
- const codeExecutionResult = yield new __await(codeExecutor.executeCode({
640
- invocationContext,
641
- codeExecutionInput: {
642
- code: codeStr,
643
- inputFiles: codeExecutorContext.getInputFiles(),
644
- executionId
645
- }
646
- }));
647
- codeExecutorContext.updateCodeExecutionResult({
648
- invocationId: invocationContext.invocationId,
649
- code: codeStr,
650
- resultStdout: codeExecutionResult.stdout,
651
- resultStderr: codeExecutionResult.stderr
652
- });
653
- yield yield new __await(postProcessCodeExecutionResult(
654
- invocationContext,
655
- codeExecutorContext,
656
- codeExecutionResult
657
- ));
658
- llmResponse.content = void 0;
659
- });
660
- }
661
- function extractAndReplaceInlineFiles(codeExecutorContext, llmRequest) {
662
- var _a2;
663
- const allInputFiles = codeExecutorContext.getInputFiles();
664
- const savedFileNames = new Set(allInputFiles.map((f) => f.name));
665
- for (let i = 0; i < llmRequest.contents.length; i++) {
666
- const content = llmRequest.contents[i];
667
- if (content.role !== "user" || !content.parts) {
668
- continue;
669
- }
670
- for (let j = 0; j < content.parts.length; j++) {
671
- const part = content.parts[j];
672
- const mimeType = (_a2 = part.inlineData) == null ? void 0 : _a2.mimeType;
673
- if (!mimeType || !part.inlineData || !DATA_FILE_UTIL_MAP[mimeType]) {
674
- continue;
675
- }
676
- const fileName = "data_".concat(i + 1, "_").concat(j + 1).concat(DATA_FILE_UTIL_MAP[mimeType].extension);
677
- part.text = "\nAvailable file: `".concat(fileName, "`\n");
678
- const file = {
679
- name: fileName,
680
- content: base64Decode(part.inlineData.data),
681
- mimeType
682
- };
683
- if (!savedFileNames.has(fileName)) {
684
- codeExecutorContext.addInputFiles([file]);
685
- allInputFiles.push(file);
686
- }
687
- }
688
- }
689
- return allInputFiles;
690
- }
691
- function getOrSetExecutionId(invocationContext, codeExecutorContext) {
692
- var _a2;
693
- const agent = invocationContext.agent;
694
- if (!isLlmAgent(agent) || !((_a2 = agent.codeExecutor) == null ? void 0 : _a2.stateful)) {
695
- return void 0;
696
- }
697
- let executionId = codeExecutorContext.getExecutionId();
698
- if (!executionId) {
699
- executionId = invocationContext.session.id;
700
- codeExecutorContext.setExecutionId(executionId);
701
- }
702
- return executionId;
703
- }
704
- async function postProcessCodeExecutionResult(invocationContext, codeExecutorContext, codeExecutionResult) {
705
- if (!invocationContext.artifactService) {
706
- throw new Error("Artifact service is not initialized.");
707
- }
708
- const resultContent = {
709
- role: "model",
710
- parts: [buildCodeExecutionResultPart(codeExecutionResult)]
711
- };
712
- const eventActions = createEventActions({
713
- stateDelta: codeExecutorContext.getStateDelta()
714
- });
715
- if (codeExecutionResult.stderr) {
716
- codeExecutorContext.incrementErrorCount(invocationContext.invocationId);
717
- } else {
718
- codeExecutorContext.resetErrorCount(invocationContext.invocationId);
719
- }
720
- for (const outputFile of codeExecutionResult.outputFiles) {
721
- const version = await invocationContext.artifactService.saveArtifact({
722
- appName: invocationContext.appName || "",
723
- userId: invocationContext.userId || "",
724
- sessionId: invocationContext.session.id,
725
- filename: outputFile.name,
726
- artifact: {
727
- inlineData: { data: outputFile.content, mimeType: outputFile.mimeType }
728
- }
729
- });
730
- eventActions.artifactDelta[outputFile.name] = version;
731
- }
732
- return createEvent({
733
- invocationId: invocationContext.invocationId,
734
- author: invocationContext.agent.name,
735
- branch: invocationContext.branch,
736
- content: resultContent,
737
- actions: eventActions
738
- });
739
- }
740
- function getDataFilePreprocessingCode(file) {
741
- function getNormalizedFileName(fileName) {
742
- const [varName2] = fileName.split(".");
743
- let normalizedName = varName2.replace(/[^a-zA-Z0-9_]/g, "_");
744
- if (/^\d/.test(normalizedName)) {
745
- normalizedName = "_" + normalizedName;
746
- }
747
- return normalizedName;
748
- }
749
- if (!DATA_FILE_UTIL_MAP[file.mimeType]) {
750
- return void 0;
751
- }
752
- const varName = getNormalizedFileName(file.name);
753
- const loaderCode = DATA_FILE_UTIL_MAP[file.mimeType].loaderCodeTemplate.replace("{filename}", file.name);
754
- return "\n".concat(DATA_FILE_HELPER_LIB, "\n\n# Load the dataframe.\n").concat(varName, " = ").concat(loaderCode, "\n\n# Use `explore_df` to guide my analysis.\nexplore_df(").concat(varName, ")\n");
755
- }
756
- const CODE_EXECUTION_REQUEST_PROCESSOR = new CodeExecutionRequestProcessor();
757
113
  const LLM_AGENT_SIGNATURE_SYMBOL = Symbol.for("google.adk.llmAgent");
758
114
  function isLlmAgent(obj) {
759
115
  return typeof obj === "object" && obj !== null && LLM_AGENT_SIGNATURE_SYMBOL in obj && obj[LLM_AGENT_SIGNATURE_SYMBOL] === true;
@@ -772,8 +128,8 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
772
128
  this.disallowTransferToParent = (_d = config.disallowTransferToParent) != null ? _d : false;
773
129
  this.disallowTransferToPeers = (_e = config.disallowTransferToPeers) != null ? _e : false;
774
130
  this.includeContents = (_f = config.includeContents) != null ? _f : "default";
775
- this.inputSchema = config.inputSchema;
776
- this.outputSchema = config.outputSchema;
131
+ this.inputSchema = isZodObject(config.inputSchema) ? zodObjectToSchema(config.inputSchema) : config.inputSchema;
132
+ this.outputSchema = isZodObject(config.outputSchema) ? zodObjectToSchema(config.outputSchema) : config.outputSchema;
777
133
  this.outputKey = config.outputKey;
778
134
  this.beforeModelCallback = config.beforeModelCallback;
779
135
  this.afterModelCallback = config.afterModelCallback;
@@ -818,16 +174,6 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
818
174
  this.disallowTransferToParent = true;
819
175
  this.disallowTransferToPeers = true;
820
176
  }
821
- if (this.subAgents && this.subAgents.length > 0) {
822
- throw new Error(
823
- "Invalid config for agent ".concat(this.name, ": if outputSchema is set, subAgents must be empty to disable agent transfer.")
824
- );
825
- }
826
- if (this.tools && this.tools.length > 0) {
827
- throw new Error(
828
- "Invalid config for agent ".concat(this.name, ": if outputSchema is set, tools must be empty")
829
- );
830
- }
831
177
  }
832
178
  }
833
179
  /**
@@ -1091,7 +437,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1091
437
  }
1092
438
  }
1093
439
  for (const toolUnion of this.tools) {
1094
- const toolContext = new ToolContext({ invocationContext });
440
+ const toolContext = new Context({ invocationContext });
1095
441
  const tools = yield new __await(convertToolUnionToTools(
1096
442
  toolUnion,
1097
443
  new ReadonlyContext(invocationContext)
@@ -1115,46 +461,56 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1115
461
  this,
1116
462
  function() {
1117
463
  return __asyncGenerator(this, null, function* () {
1118
- try {
1119
- for (var iter3 = __forAwait(this.callLlmAsync(
1120
- invocationContext,
1121
- llmRequest,
1122
- modelResponseEvent
1123
- )), more3, temp3, error3; more3 = !(temp3 = yield new __await(iter3.next())).done; more3 = false) {
1124
- const llmResponse = temp3.value;
464
+ const responsesGenerator = function() {
465
+ return __asyncGenerator(this, null, function* () {
1125
466
  try {
1126
- for (var iter2 = __forAwait(this.postprocess(
467
+ for (var iter3 = __forAwait(this.callLlmAsync(
1127
468
  invocationContext,
1128
469
  llmRequest,
1129
- llmResponse,
1130
470
  modelResponseEvent
1131
- )), more2, temp2, error2; more2 = !(temp2 = yield new __await(iter2.next())).done; more2 = false) {
1132
- const event = temp2.value;
1133
- modelResponseEvent.id = createNewEventId();
1134
- modelResponseEvent.timestamp = (/* @__PURE__ */ new Date()).getTime();
1135
- yield event;
471
+ )), more3, temp3, error3; more3 = !(temp3 = yield new __await(iter3.next())).done; more3 = false) {
472
+ const llmResponse = temp3.value;
473
+ try {
474
+ for (var iter2 = __forAwait(this.postprocess(
475
+ invocationContext,
476
+ llmRequest,
477
+ llmResponse,
478
+ modelResponseEvent
479
+ )), more2, temp2, error2; more2 = !(temp2 = yield new __await(iter2.next())).done; more2 = false) {
480
+ const event = temp2.value;
481
+ modelResponseEvent.id = createNewEventId();
482
+ modelResponseEvent.timestamp = (/* @__PURE__ */ new Date()).getTime();
483
+ yield event;
484
+ }
485
+ } catch (temp2) {
486
+ error2 = [temp2];
487
+ } finally {
488
+ try {
489
+ more2 && (temp2 = iter2.return) && (yield new __await(temp2.call(iter2)));
490
+ } finally {
491
+ if (error2)
492
+ throw error2[0];
493
+ }
494
+ }
1136
495
  }
1137
- } catch (temp2) {
1138
- error2 = [temp2];
496
+ } catch (temp3) {
497
+ error3 = [temp3];
1139
498
  } finally {
1140
499
  try {
1141
- more2 && (temp2 = iter2.return) && (yield new __await(temp2.call(iter2)));
500
+ more3 && (temp3 = iter3.return) && (yield new __await(temp3.call(iter3)));
1142
501
  } finally {
1143
- if (error2)
1144
- throw error2[0];
502
+ if (error3)
503
+ throw error3[0];
1145
504
  }
1146
505
  }
1147
- }
1148
- } catch (temp3) {
1149
- error3 = [temp3];
1150
- } finally {
1151
- try {
1152
- more3 && (temp3 = iter3.return) && (yield new __await(temp3.call(iter3)));
1153
- } finally {
1154
- if (error3)
1155
- throw error3[0];
1156
- }
1157
- }
506
+ });
507
+ };
508
+ yield* __yieldStar(this.runAndHandleError(
509
+ responsesGenerator.call(this),
510
+ invocationContext,
511
+ llmRequest,
512
+ modelResponseEvent
513
+ ));
1158
514
  });
1159
515
  }
1160
516
  ));
@@ -1163,7 +519,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1163
519
  }
1164
520
  postprocess(invocationContext, llmRequest, llmResponse, modelResponseEvent) {
1165
521
  return __asyncGenerator(this, null, function* () {
1166
- var _a2;
522
+ var _a2, _b2;
1167
523
  for (const processor of this.responseProcessors) {
1168
524
  try {
1169
525
  for (var iter = __forAwait(processor.runAsync(
@@ -1201,6 +557,10 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1201
557
  if (!((_a2 = getFunctionCalls(mergedEvent)) == null ? void 0 : _a2.length)) {
1202
558
  return;
1203
559
  }
560
+ if ((_b2 = invocationContext.runConfig) == null ? void 0 : _b2.pauseOnToolCalls) {
561
+ invocationContext.endInvocation = true;
562
+ return;
563
+ }
1204
564
  const functionResponseEvent = yield new __await(handleFunctionCallsAsync({
1205
565
  invocationContext,
1206
566
  functionCallEvent: mergedEvent,
@@ -1225,6 +585,8 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1225
585
  });
1226
586
  if (toolConfirmationEvent) {
1227
587
  yield toolConfirmationEvent;
588
+ invocationContext.endInvocation = true;
589
+ return;
1228
590
  }
1229
591
  yield functionResponseEvent;
1230
592
  const nextAgentName = functionResponseEvent.actions.transferToAgent;
@@ -1296,12 +658,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1296
658
  ((_e = invocationContext.runConfig) == null ? void 0 : _e.streamingMode) === StreamingMode.SSE
1297
659
  );
1298
660
  try {
1299
- for (var iter = __forAwait(this.runAndHandleError(
1300
- responsesGenerator,
1301
- invocationContext,
1302
- llmRequest,
1303
- modelResponseEvent
1304
- )), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
661
+ for (var iter = __forAwait(responsesGenerator), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
1305
662
  const llmResponse = temp.value;
1306
663
  traceCallLlm({
1307
664
  invocationContext,
@@ -1330,7 +687,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1330
687
  });
1331
688
  }
1332
689
  async handleBeforeModelCallback(invocationContext, llmRequest, modelResponseEvent) {
1333
- const callbackContext = new CallbackContext({
690
+ const callbackContext = new Context({
1334
691
  invocationContext,
1335
692
  eventActions: modelResponseEvent.actions
1336
693
  });
@@ -1353,7 +710,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1353
710
  return void 0;
1354
711
  }
1355
712
  async handleAfterModelCallback(invocationContext, llmResponse, modelResponseEvent) {
1356
- const callbackContext = new CallbackContext({
713
+ const callbackContext = new Context({
1357
714
  invocationContext,
1358
715
  eventActions: modelResponseEvent.actions
1359
716
  });
@@ -1394,7 +751,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1394
751
  }
1395
752
  }
1396
753
  } catch (modelError) {
1397
- const callbackContext = new CallbackContext({
754
+ const callbackContext = new Context({
1398
755
  invocationContext,
1399
756
  eventActions: modelResponseEvent.actions
1400
757
  });
@@ -1407,11 +764,29 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1407
764
  if (onModelErrorCallbackResponse) {
1408
765
  yield onModelErrorCallbackResponse;
1409
766
  } else {
1410
- const errorResponse = JSON.parse(modelError.message);
1411
- yield {
1412
- errorCode: String(errorResponse.error.code),
1413
- errorMessage: errorResponse.error.message
1414
- };
767
+ let errorCode = "UNKNOWN_ERROR";
768
+ let errorMessage = modelError.message;
769
+ try {
770
+ const errorResponse = JSON.parse(modelError.message);
771
+ if (errorResponse == null ? void 0 : errorResponse.error) {
772
+ errorCode = String(errorResponse.error.code || "UNKNOWN_ERROR");
773
+ errorMessage = errorResponse.error.message || errorMessage;
774
+ }
775
+ } catch (e) {
776
+ }
777
+ if (modelResponseEvent.actions) {
778
+ yield createEvent({
779
+ invocationId: invocationContext.invocationId,
780
+ author: this.name,
781
+ errorCode,
782
+ errorMessage
783
+ });
784
+ } else {
785
+ yield {
786
+ errorCode,
787
+ errorMessage
788
+ };
789
+ }
1415
790
  }
1416
791
  } else {
1417
792
  logger.error("Unknown error during response generation", modelError);
@@ -1429,7 +804,5 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1429
804
  }
1430
805
  export {
1431
806
  LlmAgent,
1432
- REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
1433
- isLlmAgent,
1434
- responseProcessor
807
+ isLlmAgent
1435
808
  };