@paean-ai/adk 0.2.14 → 0.2.15

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 (254) hide show
  1. package/dist/cjs/index.js +11 -11
  2. package/dist/cjs/index.js.map +3 -3
  3. package/dist/esm/index.js +11 -11
  4. package/dist/esm/index.js.map +3 -3
  5. package/dist/types/agents/llm_agent.d.ts +4 -0
  6. package/dist/web/index.js +1 -1
  7. package/dist/web/index.js.map +3 -3
  8. package/package.json +1 -1
  9. package/dist/cjs/agents/active_streaming_tool.js +0 -44
  10. package/dist/cjs/agents/base_agent.js +0 -245
  11. package/dist/cjs/agents/base_llm_processor.js +0 -44
  12. package/dist/cjs/agents/callback_context.js +0 -98
  13. package/dist/cjs/agents/content_processor_utils.js +0 -346
  14. package/dist/cjs/agents/functions.js +0 -385
  15. package/dist/cjs/agents/instructions.js +0 -110
  16. package/dist/cjs/agents/invocation_context.js +0 -107
  17. package/dist/cjs/agents/live_request_queue.js +0 -136
  18. package/dist/cjs/agents/llm_agent.js +0 -1212
  19. package/dist/cjs/agents/loop_agent.js +0 -68
  20. package/dist/cjs/agents/parallel_agent.js +0 -78
  21. package/dist/cjs/agents/readonly_context.js +0 -68
  22. package/dist/cjs/agents/run_config.js +0 -70
  23. package/dist/cjs/agents/sequential_agent.js +0 -84
  24. package/dist/cjs/agents/transcription_entry.js +0 -27
  25. package/dist/cjs/artifacts/base_artifact_service.js +0 -27
  26. package/dist/cjs/artifacts/gcs_artifact_service.js +0 -140
  27. package/dist/cjs/artifacts/in_memory_artifact_service.js +0 -119
  28. package/dist/cjs/auth/auth_credential.js +0 -46
  29. package/dist/cjs/auth/auth_handler.js +0 -92
  30. package/dist/cjs/auth/auth_schemes.js +0 -62
  31. package/dist/cjs/auth/auth_tool.js +0 -27
  32. package/dist/cjs/auth/credential_service/base_credential_service.js +0 -27
  33. package/dist/cjs/auth/credential_service/in_memory_credential_service.js +0 -63
  34. package/dist/cjs/auth/exchanger/base_credential_exchanger.js +0 -40
  35. package/dist/cjs/auth/exchanger/credential_exchanger_registry.js +0 -59
  36. package/dist/cjs/code_executors/base_code_executor.js +0 -76
  37. package/dist/cjs/code_executors/built_in_code_executor.js +0 -58
  38. package/dist/cjs/code_executors/code_execution_utils.js +0 -142
  39. package/dist/cjs/code_executors/code_executor_context.js +0 -198
  40. package/dist/cjs/common.js +0 -181
  41. package/dist/cjs/events/event.js +0 -119
  42. package/dist/cjs/events/event_actions.js +0 -83
  43. package/dist/cjs/examples/base_example_provider.js +0 -40
  44. package/dist/cjs/examples/example.js +0 -27
  45. package/dist/cjs/examples/example_util.js +0 -107
  46. package/dist/cjs/index_web.js +0 -33
  47. package/dist/cjs/memory/base_memory_service.js +0 -27
  48. package/dist/cjs/memory/in_memory_memory_service.js +0 -97
  49. package/dist/cjs/memory/memory_entry.js +0 -27
  50. package/dist/cjs/models/base_llm.js +0 -95
  51. package/dist/cjs/models/base_llm_connection.js +0 -27
  52. package/dist/cjs/models/gemini_llm_connection.js +0 -132
  53. package/dist/cjs/models/google_llm.js +0 -559
  54. package/dist/cjs/models/llm_request.js +0 -82
  55. package/dist/cjs/models/llm_response.js +0 -71
  56. package/dist/cjs/models/registry.js +0 -121
  57. package/dist/cjs/plugins/base_plugin.js +0 -236
  58. package/dist/cjs/plugins/logging_plugin.js +0 -222
  59. package/dist/cjs/plugins/plugin_manager.js +0 -239
  60. package/dist/cjs/plugins/security_plugin.js +0 -153
  61. package/dist/cjs/runner/in_memory_runner.js +0 -58
  62. package/dist/cjs/runner/runner.js +0 -277
  63. package/dist/cjs/sessions/base_session_service.js +0 -71
  64. package/dist/cjs/sessions/in_memory_session_service.js +0 -184
  65. package/dist/cjs/sessions/session.js +0 -48
  66. package/dist/cjs/sessions/state.js +0 -101
  67. package/dist/cjs/telemetry/google_cloud.js +0 -85
  68. package/dist/cjs/telemetry/setup.js +0 -97
  69. package/dist/cjs/telemetry/tracing.js +0 -231
  70. package/dist/cjs/tools/agent_tool.js +0 -134
  71. package/dist/cjs/tools/base_tool.js +0 -107
  72. package/dist/cjs/tools/base_toolset.js +0 -76
  73. package/dist/cjs/tools/forwarding_artifact_service.js +0 -71
  74. package/dist/cjs/tools/function_tool.js +0 -101
  75. package/dist/cjs/tools/google_search_tool.js +0 -76
  76. package/dist/cjs/tools/long_running_tool.js +0 -63
  77. package/dist/cjs/tools/mcp/mcp_session_manager.js +0 -65
  78. package/dist/cjs/tools/mcp/mcp_tool.js +0 -65
  79. package/dist/cjs/tools/mcp/mcp_toolset.js +0 -61
  80. package/dist/cjs/tools/tool_confirmation.js +0 -49
  81. package/dist/cjs/tools/tool_context.js +0 -129
  82. package/dist/cjs/utils/client_labels.js +0 -56
  83. package/dist/cjs/utils/deep_clone.js +0 -44
  84. package/dist/cjs/utils/env_aware_utils.js +0 -83
  85. package/dist/cjs/utils/gemini_schema_util.js +0 -88
  86. package/dist/cjs/utils/logger.js +0 -121
  87. package/dist/cjs/utils/model_name.js +0 -76
  88. package/dist/cjs/utils/simple_zod_to_json.js +0 -191
  89. package/dist/cjs/utils/variant_utils.js +0 -55
  90. package/dist/cjs/version.js +0 -39
  91. package/dist/esm/agents/active_streaming_tool.js +0 -14
  92. package/dist/esm/agents/base_agent.js +0 -214
  93. package/dist/esm/agents/base_llm_processor.js +0 -13
  94. package/dist/esm/agents/callback_context.js +0 -68
  95. package/dist/esm/agents/content_processor_utils.js +0 -315
  96. package/dist/esm/agents/functions.js +0 -344
  97. package/dist/esm/agents/instructions.js +0 -80
  98. package/dist/esm/agents/invocation_context.js +0 -76
  99. package/dist/esm/agents/live_request_queue.js +0 -106
  100. package/dist/esm/agents/llm_agent.js +0 -1180
  101. package/dist/esm/agents/loop_agent.js +0 -38
  102. package/dist/esm/agents/parallel_agent.js +0 -48
  103. package/dist/esm/agents/readonly_context.js +0 -38
  104. package/dist/esm/agents/run_config.js +0 -39
  105. package/dist/esm/agents/sequential_agent.js +0 -54
  106. package/dist/esm/agents/transcription_entry.js +0 -5
  107. package/dist/esm/artifacts/base_artifact_service.js +0 -5
  108. package/dist/esm/artifacts/gcs_artifact_service.js +0 -110
  109. package/dist/esm/artifacts/in_memory_artifact_service.js +0 -89
  110. package/dist/esm/auth/auth_credential.js +0 -16
  111. package/dist/esm/auth/auth_handler.js +0 -62
  112. package/dist/esm/auth/auth_schemes.js +0 -31
  113. package/dist/esm/auth/auth_tool.js +0 -5
  114. package/dist/esm/auth/credential_service/base_credential_service.js +0 -5
  115. package/dist/esm/auth/credential_service/in_memory_credential_service.js +0 -33
  116. package/dist/esm/auth/exchanger/base_credential_exchanger.js +0 -10
  117. package/dist/esm/auth/exchanger/credential_exchanger_registry.js +0 -29
  118. package/dist/esm/code_executors/base_code_executor.js +0 -46
  119. package/dist/esm/code_executors/built_in_code_executor.js +0 -28
  120. package/dist/esm/code_executors/code_execution_utils.js +0 -108
  121. package/dist/esm/code_executors/code_executor_context.js +0 -168
  122. package/dist/esm/common.js +0 -98
  123. package/dist/esm/events/event.js +0 -83
  124. package/dist/esm/events/event_actions.js +0 -52
  125. package/dist/esm/examples/base_example_provider.js +0 -10
  126. package/dist/esm/examples/example.js +0 -5
  127. package/dist/esm/examples/example_util.js +0 -76
  128. package/dist/esm/index_web.js +0 -6
  129. package/dist/esm/memory/base_memory_service.js +0 -5
  130. package/dist/esm/memory/in_memory_memory_service.js +0 -67
  131. package/dist/esm/memory/memory_entry.js +0 -5
  132. package/dist/esm/models/base_llm.js +0 -64
  133. package/dist/esm/models/base_llm_connection.js +0 -5
  134. package/dist/esm/models/gemini_llm_connection.js +0 -102
  135. package/dist/esm/models/google_llm.js +0 -533
  136. package/dist/esm/models/llm_request.js +0 -50
  137. package/dist/esm/models/llm_response.js +0 -41
  138. package/dist/esm/models/registry.js +0 -91
  139. package/dist/esm/plugins/base_plugin.js +0 -206
  140. package/dist/esm/plugins/logging_plugin.js +0 -192
  141. package/dist/esm/plugins/plugin_manager.js +0 -209
  142. package/dist/esm/plugins/security_plugin.js +0 -119
  143. package/dist/esm/runner/in_memory_runner.js +0 -28
  144. package/dist/esm/runner/runner.js +0 -247
  145. package/dist/esm/sessions/base_session_service.js +0 -41
  146. package/dist/esm/sessions/in_memory_session_service.js +0 -154
  147. package/dist/esm/sessions/session.js +0 -18
  148. package/dist/esm/sessions/state.js +0 -71
  149. package/dist/esm/telemetry/google_cloud.js +0 -54
  150. package/dist/esm/telemetry/setup.js +0 -67
  151. package/dist/esm/telemetry/tracing.js +0 -195
  152. package/dist/esm/tools/agent_tool.js +0 -104
  153. package/dist/esm/tools/base_tool.js +0 -77
  154. package/dist/esm/tools/base_toolset.js +0 -46
  155. package/dist/esm/tools/forwarding_artifact_service.js +0 -41
  156. package/dist/esm/tools/function_tool.js +0 -71
  157. package/dist/esm/tools/google_search_tool.js +0 -46
  158. package/dist/esm/tools/long_running_tool.js +0 -33
  159. package/dist/esm/tools/mcp/mcp_session_manager.js +0 -35
  160. package/dist/esm/tools/mcp/mcp_tool.js +0 -35
  161. package/dist/esm/tools/mcp/mcp_toolset.js +0 -31
  162. package/dist/esm/tools/tool_confirmation.js +0 -19
  163. package/dist/esm/tools/tool_context.js +0 -99
  164. package/dist/esm/utils/client_labels.js +0 -26
  165. package/dist/esm/utils/deep_clone.js +0 -14
  166. package/dist/esm/utils/env_aware_utils.js +0 -49
  167. package/dist/esm/utils/gemini_schema_util.js +0 -58
  168. package/dist/esm/utils/logger.js +0 -89
  169. package/dist/esm/utils/model_name.js +0 -41
  170. package/dist/esm/utils/simple_zod_to_json.js +0 -160
  171. package/dist/esm/utils/variant_utils.js +0 -24
  172. package/dist/esm/version.js +0 -9
  173. package/dist/web/agents/active_streaming_tool.js +0 -14
  174. package/dist/web/agents/base_agent.js +0 -265
  175. package/dist/web/agents/base_llm_processor.js +0 -13
  176. package/dist/web/agents/callback_context.js +0 -68
  177. package/dist/web/agents/content_processor_utils.js +0 -315
  178. package/dist/web/agents/functions.js +0 -344
  179. package/dist/web/agents/instructions.js +0 -80
  180. package/dist/web/agents/invocation_context.js +0 -76
  181. package/dist/web/agents/live_request_queue.js +0 -124
  182. package/dist/web/agents/llm_agent.js +0 -1310
  183. package/dist/web/agents/loop_agent.js +0 -71
  184. package/dist/web/agents/parallel_agent.js +0 -83
  185. package/dist/web/agents/readonly_context.js +0 -38
  186. package/dist/web/agents/run_config.js +0 -54
  187. package/dist/web/agents/sequential_agent.js +0 -99
  188. package/dist/web/agents/transcription_entry.js +0 -5
  189. package/dist/web/artifacts/base_artifact_service.js +0 -5
  190. package/dist/web/artifacts/gcs_artifact_service.js +0 -126
  191. package/dist/web/artifacts/in_memory_artifact_service.js +0 -89
  192. package/dist/web/auth/auth_credential.js +0 -16
  193. package/dist/web/auth/auth_handler.js +0 -62
  194. package/dist/web/auth/auth_schemes.js +0 -31
  195. package/dist/web/auth/auth_tool.js +0 -5
  196. package/dist/web/auth/credential_service/base_credential_service.js +0 -5
  197. package/dist/web/auth/credential_service/in_memory_credential_service.js +0 -33
  198. package/dist/web/auth/exchanger/base_credential_exchanger.js +0 -10
  199. package/dist/web/auth/exchanger/credential_exchanger_registry.js +0 -29
  200. package/dist/web/code_executors/base_code_executor.js +0 -46
  201. package/dist/web/code_executors/built_in_code_executor.js +0 -28
  202. package/dist/web/code_executors/code_execution_utils.js +0 -105
  203. package/dist/web/code_executors/code_executor_context.js +0 -168
  204. package/dist/web/common.js +0 -98
  205. package/dist/web/events/event.js +0 -101
  206. package/dist/web/events/event_actions.js +0 -67
  207. package/dist/web/examples/base_example_provider.js +0 -10
  208. package/dist/web/examples/example.js +0 -5
  209. package/dist/web/examples/example_util.js +0 -75
  210. package/dist/web/index_web.js +0 -6
  211. package/dist/web/memory/base_memory_service.js +0 -5
  212. package/dist/web/memory/in_memory_memory_service.js +0 -67
  213. package/dist/web/memory/memory_entry.js +0 -5
  214. package/dist/web/models/base_llm.js +0 -64
  215. package/dist/web/models/base_llm_connection.js +0 -5
  216. package/dist/web/models/gemini_llm_connection.js +0 -120
  217. package/dist/web/models/google_llm.js +0 -574
  218. package/dist/web/models/llm_request.js +0 -50
  219. package/dist/web/models/llm_response.js +0 -41
  220. package/dist/web/models/registry.js +0 -91
  221. package/dist/web/plugins/base_plugin.js +0 -206
  222. package/dist/web/plugins/logging_plugin.js +0 -192
  223. package/dist/web/plugins/plugin_manager.js +0 -209
  224. package/dist/web/plugins/security_plugin.js +0 -119
  225. package/dist/web/runner/in_memory_runner.js +0 -28
  226. package/dist/web/runner/runner.js +0 -278
  227. package/dist/web/sessions/base_session_service.js +0 -41
  228. package/dist/web/sessions/in_memory_session_service.js +0 -154
  229. package/dist/web/sessions/session.js +0 -18
  230. package/dist/web/sessions/state.js +0 -87
  231. package/dist/web/telemetry/google_cloud.js +0 -54
  232. package/dist/web/telemetry/setup.js +0 -67
  233. package/dist/web/telemetry/tracing.js +0 -210
  234. package/dist/web/tools/agent_tool.js +0 -118
  235. package/dist/web/tools/base_tool.js +0 -77
  236. package/dist/web/tools/base_toolset.js +0 -46
  237. package/dist/web/tools/forwarding_artifact_service.js +0 -41
  238. package/dist/web/tools/function_tool.js +0 -71
  239. package/dist/web/tools/google_search_tool.js +0 -46
  240. package/dist/web/tools/long_running_tool.js +0 -50
  241. package/dist/web/tools/mcp/mcp_session_manager.js +0 -35
  242. package/dist/web/tools/mcp/mcp_tool.js +0 -35
  243. package/dist/web/tools/mcp/mcp_toolset.js +0 -31
  244. package/dist/web/tools/tool_confirmation.js +0 -19
  245. package/dist/web/tools/tool_context.js +0 -99
  246. package/dist/web/utils/client_labels.js +0 -26
  247. package/dist/web/utils/deep_clone.js +0 -14
  248. package/dist/web/utils/env_aware_utils.js +0 -49
  249. package/dist/web/utils/gemini_schema_util.js +0 -58
  250. package/dist/web/utils/logger.js +0 -89
  251. package/dist/web/utils/model_name.js +0 -41
  252. package/dist/web/utils/simple_zod_to_json.js +0 -174
  253. package/dist/web/utils/variant_utils.js +0 -24
  254. package/dist/web/version.js +0 -9
@@ -1,1310 +0,0 @@
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 { BaseCodeExecutor } from "../code_executors/base_code_executor.js";
41
- import { BuiltInCodeExecutor } from "../code_executors/built_in_code_executor.js";
42
- import { buildCodeExecutionResultPart, buildExecutableCodePart, convertCodeExecutionParts, extractCodeAndTruncateContent } from "../code_executors/code_execution_utils.js";
43
- import { CodeExecutorContext } from "../code_executors/code_executor_context.js";
44
- import { createEvent, createNewEventId, getFunctionCalls, getFunctionResponses, isFinalResponse } from "../events/event.js";
45
- import { createEventActions } from "../events/event_actions.js";
46
- import { isBaseLlm } from "../models/base_llm.js";
47
- import { appendInstructions, setOutputSchema } from "../models/llm_request.js";
48
- import { LLMRegistry } from "../models/registry.js";
49
- import { State } from "../sessions/state.js";
50
- import { BaseTool } from "../tools/base_tool.js";
51
- import { FunctionTool } from "../tools/function_tool.js";
52
- import { ToolConfirmation } from "../tools/tool_confirmation.js";
53
- import { ToolContext } from "../tools/tool_context.js";
54
- import { deepClone } from "../utils/deep_clone.js";
55
- import { base64Decode } from "../utils/env_aware_utils.js";
56
- import { logger } from "../utils/logger.js";
57
- import { BaseAgent } from "./base_agent.js";
58
- import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
59
- import { CallbackContext } from "./callback_context.js";
60
- import { getContents, getCurrentTurnContents } from "./content_processor_utils.js";
61
- import { generateAuthEvent, generateRequestConfirmationEvent, getLongRunningFunctionCalls, handleFunctionCallList, handleFunctionCallsAsync, populateClientFunctionCallId, REQUEST_CONFIRMATION_FUNCTION_CALL_NAME } from "./functions.js";
62
- import { injectSessionState } from "./instructions.js";
63
- import { ReadonlyContext } from "./readonly_context.js";
64
- import { StreamingMode } from "./run_config.js";
65
- const ADK_AGENT_NAME_LABEL_KEY = "adk_agent_name";
66
- async function convertToolUnionToTools(toolUnion, context) {
67
- if (toolUnion instanceof BaseTool) {
68
- return [toolUnion];
69
- }
70
- return await toolUnion.getTools(context);
71
- }
72
- class BasicLlmRequestProcessor extends BaseLlmRequestProcessor {
73
- runAsync(invocationContext, llmRequest) {
74
- return __asyncGenerator(this, null, function* () {
75
- var _a;
76
- const agent = invocationContext.agent;
77
- if (!(agent instanceof LlmAgent)) {
78
- return;
79
- }
80
- llmRequest.model = agent.canonicalModel.model;
81
- llmRequest.config = __spreadValues({}, (_a = agent.generateContentConfig) != null ? _a : {});
82
- if (agent.outputSchema) {
83
- setOutputSchema(llmRequest, agent.outputSchema);
84
- }
85
- if (invocationContext.runConfig) {
86
- llmRequest.liveConnectConfig.responseModalities = invocationContext.runConfig.responseModalities;
87
- llmRequest.liveConnectConfig.speechConfig = invocationContext.runConfig.speechConfig;
88
- llmRequest.liveConnectConfig.outputAudioTranscription = invocationContext.runConfig.outputAudioTranscription;
89
- llmRequest.liveConnectConfig.inputAudioTranscription = invocationContext.runConfig.inputAudioTranscription;
90
- llmRequest.liveConnectConfig.realtimeInputConfig = invocationContext.runConfig.realtimeInputConfig;
91
- llmRequest.liveConnectConfig.enableAffectiveDialog = invocationContext.runConfig.enableAffectiveDialog;
92
- llmRequest.liveConnectConfig.proactivity = invocationContext.runConfig.proactivity;
93
- }
94
- });
95
- }
96
- }
97
- const BASIC_LLM_REQUEST_PROCESSOR = new BasicLlmRequestProcessor();
98
- class IdentityLlmRequestProcessor extends BaseLlmRequestProcessor {
99
- runAsync(invocationContext, llmRequest) {
100
- return __asyncGenerator(this, null, function* () {
101
- const agent = invocationContext.agent;
102
- const si = ['You are an agent. Your internal name is "'.concat(agent.name, '".')];
103
- if (agent.description) {
104
- si.push('The description about you is "'.concat(agent.description, '"'));
105
- }
106
- appendInstructions(llmRequest, si);
107
- });
108
- }
109
- }
110
- const IDENTITY_LLM_REQUEST_PROCESSOR = new IdentityLlmRequestProcessor();
111
- class InstructionsLlmRequestProcessor extends BaseLlmRequestProcessor {
112
- /**
113
- * Handles instructions and global instructions for LLM flow.
114
- */
115
- runAsync(invocationContext, llmRequest) {
116
- return __asyncGenerator(this, null, function* () {
117
- const agent = invocationContext.agent;
118
- if (!(agent instanceof LlmAgent) || !(agent.rootAgent instanceof LlmAgent)) {
119
- return;
120
- }
121
- const rootAgent = agent.rootAgent;
122
- if (rootAgent instanceof LlmAgent && rootAgent.globalInstruction) {
123
- const { instruction, requireStateInjection } = yield new __await(rootAgent.canonicalGlobalInstruction(
124
- new ReadonlyContext(invocationContext)
125
- ));
126
- let instructionWithState = instruction;
127
- if (requireStateInjection) {
128
- instructionWithState = yield new __await(injectSessionState(
129
- instruction,
130
- new ReadonlyContext(invocationContext)
131
- ));
132
- }
133
- appendInstructions(llmRequest, [instructionWithState]);
134
- }
135
- if (agent.instruction) {
136
- const { instruction, requireStateInjection } = yield new __await(agent.canonicalInstruction(
137
- new ReadonlyContext(invocationContext)
138
- ));
139
- let instructionWithState = instruction;
140
- if (requireStateInjection) {
141
- instructionWithState = yield new __await(injectSessionState(
142
- instruction,
143
- new ReadonlyContext(invocationContext)
144
- ));
145
- }
146
- appendInstructions(llmRequest, [instructionWithState]);
147
- }
148
- });
149
- }
150
- }
151
- const INSTRUCTIONS_LLM_REQUEST_PROCESSOR = new InstructionsLlmRequestProcessor();
152
- class ContentRequestProcessor {
153
- runAsync(invocationContext, llmRequest) {
154
- return __asyncGenerator(this, null, function* () {
155
- const agent = invocationContext.agent;
156
- if (!agent || !(agent instanceof LlmAgent)) {
157
- return;
158
- }
159
- if (agent.includeContents === "default") {
160
- llmRequest.contents = getContents(
161
- invocationContext.session.events,
162
- agent.name,
163
- invocationContext.branch
164
- );
165
- } else {
166
- llmRequest.contents = getCurrentTurnContents(
167
- invocationContext.session.events,
168
- agent.name,
169
- invocationContext.branch
170
- );
171
- }
172
- return;
173
- });
174
- }
175
- }
176
- const CONTENT_REQUEST_PROCESSOR = new ContentRequestProcessor();
177
- class AgentTransferLlmRequestProcessor extends BaseLlmRequestProcessor {
178
- constructor() {
179
- super(...arguments);
180
- this.toolName = "transfer_to_agent";
181
- this.tool = new FunctionTool({
182
- name: this.toolName,
183
- 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.",
184
- parameters: z.object({
185
- agentName: z.string().describe("the agent name to transfer to.")
186
- }),
187
- execute: function(args, toolContext) {
188
- if (!toolContext) {
189
- throw new Error("toolContext is required.");
190
- }
191
- toolContext.actions.transferToAgent = args.agentName;
192
- return "Transfer queued";
193
- }
194
- });
195
- }
196
- runAsync(invocationContext, llmRequest) {
197
- return __asyncGenerator(this, null, function* () {
198
- if (!(invocationContext.agent instanceof LlmAgent)) {
199
- return;
200
- }
201
- const transferTargets = this.getTransferTargets(invocationContext.agent);
202
- if (!transferTargets.length) {
203
- return;
204
- }
205
- appendInstructions(llmRequest, [
206
- this.buildTargetAgentsInstructions(
207
- invocationContext.agent,
208
- transferTargets
209
- )
210
- ]);
211
- const toolContext = new ToolContext({ invocationContext });
212
- yield new __await(this.tool.processLlmRequest({ toolContext, llmRequest }));
213
- });
214
- }
215
- buildTargetAgentsInfo(targetAgent) {
216
- return "\nAgent name: ".concat(targetAgent.name, "\nAgent description: ").concat(targetAgent.description, "\n");
217
- }
218
- buildTargetAgentsInstructions(agent, targetAgents) {
219
- 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");
220
- if (agent.parentAgent && !agent.disallowTransferToParent) {
221
- 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");
222
- }
223
- return instructions;
224
- }
225
- getTransferTargets(agent) {
226
- const targets = [];
227
- targets.push(...agent.subAgents);
228
- if (!agent.parentAgent || !(agent.parentAgent instanceof LlmAgent)) {
229
- return targets;
230
- }
231
- if (!agent.disallowTransferToParent) {
232
- targets.push(agent.parentAgent);
233
- }
234
- if (!agent.disallowTransferToPeers) {
235
- targets.push(
236
- ...agent.parentAgent.subAgents.filter(
237
- (peerAgent) => peerAgent.name !== agent.name
238
- )
239
- );
240
- }
241
- return targets;
242
- }
243
- }
244
- const AGENT_TRANSFER_LLM_REQUEST_PROCESSOR = new AgentTransferLlmRequestProcessor();
245
- class RequestConfirmationLlmRequestProcessor extends BaseLlmRequestProcessor {
246
- /** Handles tool confirmation information to build the LLM request. */
247
- runAsync(invocationContext, llmRequest) {
248
- return __asyncGenerator(this, null, function* () {
249
- const agent = invocationContext.agent;
250
- if (!(agent instanceof LlmAgent)) {
251
- return;
252
- }
253
- const events = invocationContext.session.events;
254
- if (!events || events.length === 0) {
255
- return;
256
- }
257
- const requestConfirmationFunctionResponses = {};
258
- let confirmationEventIndex = -1;
259
- for (let i = events.length - 1; i >= 0; i--) {
260
- const event = events[i];
261
- if (event.author !== "user") {
262
- continue;
263
- }
264
- const responses = getFunctionResponses(event);
265
- if (!responses) {
266
- continue;
267
- }
268
- let foundConfirmation = false;
269
- for (const functionResponse of responses) {
270
- if (functionResponse.name !== REQUEST_CONFIRMATION_FUNCTION_CALL_NAME) {
271
- continue;
272
- }
273
- foundConfirmation = true;
274
- let toolConfirmation = null;
275
- if (functionResponse.response && Object.keys(functionResponse.response).length === 1 && "response" in functionResponse.response) {
276
- toolConfirmation = JSON.parse(functionResponse.response["response"]);
277
- } else if (functionResponse.response) {
278
- toolConfirmation = new ToolConfirmation({
279
- hint: functionResponse.response["hint"],
280
- payload: functionResponse.response["payload"],
281
- confirmed: functionResponse.response["confirmed"]
282
- });
283
- }
284
- if (functionResponse.id && toolConfirmation) {
285
- requestConfirmationFunctionResponses[functionResponse.id] = toolConfirmation;
286
- }
287
- }
288
- if (foundConfirmation) {
289
- confirmationEventIndex = i;
290
- break;
291
- }
292
- }
293
- if (Object.keys(requestConfirmationFunctionResponses).length === 0) {
294
- return;
295
- }
296
- for (let i = confirmationEventIndex - 1; i >= 0; i--) {
297
- const event = events[i];
298
- const functionCalls = getFunctionCalls(event);
299
- if (!functionCalls) {
300
- continue;
301
- }
302
- const toolsToResumeWithConfirmation = {};
303
- const toolsToResumeWithArgs = {};
304
- for (const functionCall of functionCalls) {
305
- if (!functionCall.id || !(functionCall.id in requestConfirmationFunctionResponses)) {
306
- continue;
307
- }
308
- const args = functionCall.args;
309
- if (!args || !("originalFunctionCall" in args)) {
310
- continue;
311
- }
312
- const originalFunctionCall = args["originalFunctionCall"];
313
- if (originalFunctionCall.id) {
314
- toolsToResumeWithConfirmation[originalFunctionCall.id] = requestConfirmationFunctionResponses[functionCall.id];
315
- toolsToResumeWithArgs[originalFunctionCall.id] = originalFunctionCall;
316
- }
317
- }
318
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
319
- continue;
320
- }
321
- for (let j = events.length - 1; j > confirmationEventIndex; j--) {
322
- const eventToCheck = events[j];
323
- const functionResponses = getFunctionResponses(eventToCheck);
324
- if (!functionResponses) {
325
- continue;
326
- }
327
- for (const fr of functionResponses) {
328
- if (fr.id && fr.id in toolsToResumeWithConfirmation) {
329
- delete toolsToResumeWithConfirmation[fr.id];
330
- delete toolsToResumeWithArgs[fr.id];
331
- }
332
- }
333
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
334
- break;
335
- }
336
- }
337
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
338
- continue;
339
- }
340
- const toolsList = yield new __await(agent.canonicalTools(new ReadonlyContext(invocationContext)));
341
- const toolsDict = Object.fromEntries(toolsList.map((tool) => [tool.name, tool]));
342
- const functionResponseEvent = yield new __await(handleFunctionCallList({
343
- invocationContext,
344
- functionCalls: Object.values(toolsToResumeWithArgs),
345
- toolsDict,
346
- beforeToolCallbacks: agent.canonicalBeforeToolCallbacks,
347
- afterToolCallbacks: agent.canonicalAfterToolCallbacks,
348
- filters: new Set(Object.keys(toolsToResumeWithConfirmation)),
349
- toolConfirmationDict: toolsToResumeWithConfirmation
350
- }));
351
- if (functionResponseEvent) {
352
- yield functionResponseEvent;
353
- }
354
- return;
355
- }
356
- });
357
- }
358
- }
359
- const REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR = new RequestConfirmationLlmRequestProcessor();
360
- class CodeExecutionRequestProcessor extends BaseLlmRequestProcessor {
361
- runAsync(invocationContext, llmRequest) {
362
- return __asyncGenerator(this, null, function* () {
363
- if (!(invocationContext.agent instanceof LlmAgent)) {
364
- return;
365
- }
366
- if (!invocationContext.agent.codeExecutor) {
367
- return;
368
- }
369
- try {
370
- for (var iter = __forAwait(runPreProcessor(invocationContext, llmRequest)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
371
- const event = temp.value;
372
- yield event;
373
- }
374
- } catch (temp) {
375
- error = [temp];
376
- } finally {
377
- try {
378
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
379
- } finally {
380
- if (error)
381
- throw error[0];
382
- }
383
- }
384
- if (!(invocationContext.agent.codeExecutor instanceof BaseCodeExecutor)) {
385
- return;
386
- }
387
- for (const content of llmRequest.contents) {
388
- const delimeters = invocationContext.agent.codeExecutor.codeBlockDelimiters.length ? invocationContext.agent.codeExecutor.codeBlockDelimiters[0] : ["", ""];
389
- const codeExecutionParts = convertCodeExecutionParts(
390
- content,
391
- delimeters,
392
- invocationContext.agent.codeExecutor.executionResultDelimiters
393
- );
394
- }
395
- });
396
- }
397
- }
398
- const DATA_FILE_UTIL_MAP = {
399
- "text/csv": {
400
- extension: ".csv",
401
- loaderCodeTemplate: "pd.read_csv('{filename}')"
402
- }
403
- };
404
- 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";
405
- class CodeExecutionResponseProcessor {
406
- /**
407
- * Processes the LLM response asynchronously.
408
- *
409
- * @param invocationContext The invocation context
410
- * @param llmResponse The LLM response to process
411
- * @returns An async generator yielding events
412
- */
413
- runAsync(invocationContext, llmResponse) {
414
- return __asyncGenerator(this, null, function* () {
415
- if (llmResponse.partial) {
416
- return;
417
- }
418
- try {
419
- for (var iter = __forAwait(runPostProcessor(invocationContext, llmResponse)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
420
- const event = temp.value;
421
- yield event;
422
- }
423
- } catch (temp) {
424
- error = [temp];
425
- } finally {
426
- try {
427
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
428
- } finally {
429
- if (error)
430
- throw error[0];
431
- }
432
- }
433
- });
434
- }
435
- }
436
- const responseProcessor = new CodeExecutionResponseProcessor();
437
- function runPreProcessor(invocationContext, llmRequest) {
438
- return __asyncGenerator(this, null, function* () {
439
- const agent = invocationContext.agent;
440
- if (!(agent instanceof LlmAgent)) {
441
- return;
442
- }
443
- const codeExecutor = agent.codeExecutor;
444
- if (!codeExecutor || !(codeExecutor instanceof BaseCodeExecutor)) {
445
- return;
446
- }
447
- if (codeExecutor instanceof BuiltInCodeExecutor) {
448
- codeExecutor.processLlmRequest(llmRequest);
449
- return;
450
- }
451
- if (!codeExecutor.optimizeDataFile) {
452
- return;
453
- }
454
- const codeExecutorContext = new CodeExecutorContext(new State(invocationContext.session.state));
455
- if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
456
- return;
457
- }
458
- const allInputFiles = extractAndReplaceInlineFiles(codeExecutorContext, llmRequest);
459
- const processedFileNames = new Set(codeExecutorContext.getProcessedFileNames());
460
- const filesToProcess = allInputFiles.filter((f) => !processedFileNames.has(f.name));
461
- for (const file of filesToProcess) {
462
- const codeStr = getDataFilePreprocessingCode(file);
463
- if (!codeStr) {
464
- return;
465
- }
466
- const codeContent = {
467
- role: "model",
468
- parts: [
469
- { text: "Processing input file: `".concat(file.name, "`") },
470
- buildExecutableCodePart(codeStr)
471
- ]
472
- };
473
- llmRequest.contents.push(deepClone(codeContent));
474
- yield createEvent({
475
- invocationId: invocationContext.invocationId,
476
- author: agent.name,
477
- branch: invocationContext.branch,
478
- content: codeContent
479
- });
480
- const executionId = getOrSetExecutionId(invocationContext, codeExecutorContext);
481
- const codeExecutionResult = yield new __await(codeExecutor.executeCode({
482
- invocationContext,
483
- codeExecutionInput: {
484
- code: codeStr,
485
- inputFiles: [file],
486
- executionId
487
- }
488
- }));
489
- codeExecutorContext.updateCodeExecutionResult({
490
- invocationId: invocationContext.invocationId,
491
- code: codeStr,
492
- resultStdout: codeExecutionResult.stdout,
493
- resultStderr: codeExecutionResult.stderr
494
- });
495
- codeExecutorContext.addProcessedFileNames([file.name]);
496
- const executionResultEvent = yield new __await(postProcessCodeExecutionResult(
497
- invocationContext,
498
- codeExecutorContext,
499
- codeExecutionResult
500
- ));
501
- yield executionResultEvent;
502
- llmRequest.contents.push(deepClone(executionResultEvent.content));
503
- }
504
- });
505
- }
506
- function runPostProcessor(invocationContext, llmResponse) {
507
- return __asyncGenerator(this, null, function* () {
508
- const agent = invocationContext.agent;
509
- if (!(agent instanceof LlmAgent)) {
510
- return;
511
- }
512
- const codeExecutor = agent.codeExecutor;
513
- if (!codeExecutor || !(codeExecutor instanceof BaseCodeExecutor)) {
514
- return;
515
- }
516
- if (!llmResponse || !llmResponse.content) {
517
- return;
518
- }
519
- if (codeExecutor instanceof BuiltInCodeExecutor) {
520
- return;
521
- }
522
- const codeExecutorContext = new CodeExecutorContext(new State(invocationContext.session.state));
523
- if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
524
- return;
525
- }
526
- const responseContent = llmResponse.content;
527
- const codeStr = extractCodeAndTruncateContent(
528
- responseContent,
529
- codeExecutor.codeBlockDelimiters
530
- );
531
- if (!codeStr) {
532
- return;
533
- }
534
- yield createEvent({
535
- invocationId: invocationContext.invocationId,
536
- author: agent.name,
537
- branch: invocationContext.branch,
538
- content: responseContent
539
- });
540
- const executionId = getOrSetExecutionId(invocationContext, codeExecutorContext);
541
- const codeExecutionResult = yield new __await(codeExecutor.executeCode({
542
- invocationContext,
543
- codeExecutionInput: {
544
- code: codeStr,
545
- inputFiles: codeExecutorContext.getInputFiles(),
546
- executionId
547
- }
548
- }));
549
- codeExecutorContext.updateCodeExecutionResult({
550
- invocationId: invocationContext.invocationId,
551
- code: codeStr,
552
- resultStdout: codeExecutionResult.stdout,
553
- resultStderr: codeExecutionResult.stderr
554
- });
555
- yield yield new __await(postProcessCodeExecutionResult(
556
- invocationContext,
557
- codeExecutorContext,
558
- codeExecutionResult
559
- ));
560
- llmResponse.content = null;
561
- });
562
- }
563
- function extractAndReplaceInlineFiles(codeExecutorContext, llmRequest) {
564
- var _a;
565
- const allInputFiles = codeExecutorContext.getInputFiles();
566
- const savedFileNames = new Set(allInputFiles.map((f) => f.name));
567
- for (let i = 0; i < llmRequest.contents.length; i++) {
568
- const content = llmRequest.contents[i];
569
- if (content.role !== "user" || !content.parts) {
570
- continue;
571
- }
572
- for (let j = 0; j < content.parts.length; j++) {
573
- const part = content.parts[j];
574
- const mimeType = (_a = part.inlineData) == null ? void 0 : _a.mimeType;
575
- if (!mimeType || !part.inlineData || !DATA_FILE_UTIL_MAP[mimeType]) {
576
- continue;
577
- }
578
- const fileName = "data_".concat(i + 1, "_").concat(j + 1).concat(DATA_FILE_UTIL_MAP[mimeType].extension);
579
- part.text = "\nAvailable file: `".concat(fileName, "`\n");
580
- const file = {
581
- name: fileName,
582
- content: base64Decode(part.inlineData.data),
583
- mimeType
584
- };
585
- if (!savedFileNames.has(fileName)) {
586
- codeExecutorContext.addInputFiles([file]);
587
- allInputFiles.push(file);
588
- }
589
- }
590
- }
591
- return allInputFiles;
592
- }
593
- function getOrSetExecutionId(invocationContext, codeExecutorContext) {
594
- var _a;
595
- const agent = invocationContext.agent;
596
- if (!(agent instanceof LlmAgent) || !((_a = agent.codeExecutor) == null ? void 0 : _a.stateful)) {
597
- return void 0;
598
- }
599
- let executionId = codeExecutorContext.getExecutionId();
600
- if (!executionId) {
601
- executionId = invocationContext.session.id;
602
- codeExecutorContext.setExecutionId(executionId);
603
- }
604
- return executionId;
605
- }
606
- async function postProcessCodeExecutionResult(invocationContext, codeExecutorContext, codeExecutionResult) {
607
- if (!invocationContext.artifactService) {
608
- throw new Error("Artifact service is not initialized.");
609
- }
610
- const resultContent = {
611
- role: "model",
612
- parts: [buildCodeExecutionResultPart(codeExecutionResult)]
613
- };
614
- const eventActions = createEventActions({ stateDelta: codeExecutorContext.getStateDelta() });
615
- if (codeExecutionResult.stderr) {
616
- codeExecutorContext.incrementErrorCount(invocationContext.invocationId);
617
- } else {
618
- codeExecutorContext.resetErrorCount(invocationContext.invocationId);
619
- }
620
- for (const outputFile of codeExecutionResult.outputFiles) {
621
- const version = await invocationContext.artifactService.saveArtifact({
622
- appName: invocationContext.appName || "",
623
- userId: invocationContext.userId || "",
624
- sessionId: invocationContext.session.id,
625
- filename: outputFile.name,
626
- artifact: {
627
- inlineData: { data: outputFile.content, mimeType: outputFile.mimeType }
628
- }
629
- });
630
- eventActions.artifactDelta[outputFile.name] = version;
631
- }
632
- return createEvent({
633
- invocationId: invocationContext.invocationId,
634
- author: invocationContext.agent.name,
635
- branch: invocationContext.branch,
636
- content: resultContent,
637
- actions: eventActions
638
- });
639
- }
640
- function getDataFilePreprocessingCode(file) {
641
- function getNormalizedFileName(fileName) {
642
- const [varName2] = fileName.split(".");
643
- let normalizedName = varName2.replace(/[^a-zA-Z0-9_]/g, "_");
644
- if (/^\d/.test(normalizedName)) {
645
- normalizedName = "_" + normalizedName;
646
- }
647
- return normalizedName;
648
- }
649
- if (!DATA_FILE_UTIL_MAP[file.mimeType]) {
650
- return void 0;
651
- }
652
- const varName = getNormalizedFileName(file.name);
653
- const loaderCode = DATA_FILE_UTIL_MAP[file.mimeType].loaderCodeTemplate.replace(
654
- "{filename}",
655
- file.name
656
- );
657
- 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");
658
- }
659
- const CODE_EXECUTION_REQUEST_PROCESSOR = new CodeExecutionRequestProcessor();
660
- class LlmAgent extends BaseAgent {
661
- constructor(config) {
662
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
663
- super(config);
664
- this.model = config.model;
665
- this.instruction = (_a = config.instruction) != null ? _a : "";
666
- this.globalInstruction = (_b = config.globalInstruction) != null ? _b : "";
667
- this.tools = (_c = config.tools) != null ? _c : [];
668
- this.generateContentConfig = config.generateContentConfig;
669
- this.disallowTransferToParent = (_d = config.disallowTransferToParent) != null ? _d : false;
670
- this.disallowTransferToPeers = (_e = config.disallowTransferToPeers) != null ? _e : false;
671
- this.includeContents = (_f = config.includeContents) != null ? _f : "default";
672
- this.inputSchema = config.inputSchema;
673
- this.outputSchema = config.outputSchema;
674
- this.outputKey = config.outputKey;
675
- this.beforeModelCallback = config.beforeModelCallback;
676
- this.afterModelCallback = config.afterModelCallback;
677
- this.beforeToolCallback = config.beforeToolCallback;
678
- this.afterToolCallback = config.afterToolCallback;
679
- this.codeExecutor = config.codeExecutor;
680
- this.requestProcessors = (_g = config.requestProcessors) != null ? _g : [
681
- BASIC_LLM_REQUEST_PROCESSOR,
682
- IDENTITY_LLM_REQUEST_PROCESSOR,
683
- INSTRUCTIONS_LLM_REQUEST_PROCESSOR,
684
- REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
685
- CONTENT_REQUEST_PROCESSOR,
686
- CODE_EXECUTION_REQUEST_PROCESSOR
687
- ];
688
- this.responseProcessors = (_h = config.responseProcessors) != null ? _h : [];
689
- const agentTransferDisabled = this.disallowTransferToParent && this.disallowTransferToPeers && !((_i = this.subAgents) == null ? void 0 : _i.length);
690
- if (!agentTransferDisabled) {
691
- this.requestProcessors.push(AGENT_TRANSFER_LLM_REQUEST_PROCESSOR);
692
- }
693
- if (config.generateContentConfig) {
694
- if (config.generateContentConfig.tools) {
695
- throw new Error("All tools must be set via LlmAgent.tools.");
696
- }
697
- if (config.generateContentConfig.systemInstruction) {
698
- throw new Error(
699
- "System instruction must be set via LlmAgent.instruction."
700
- );
701
- }
702
- if (config.generateContentConfig.responseSchema) {
703
- throw new Error(
704
- "Response schema must be set via LlmAgent.output_schema."
705
- );
706
- }
707
- } else {
708
- this.generateContentConfig = {};
709
- }
710
- if (this.outputSchema) {
711
- if (!this.disallowTransferToParent || !this.disallowTransferToPeers) {
712
- logger.warn(
713
- "Invalid config for agent ".concat(this.name, ": outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true")
714
- );
715
- this.disallowTransferToParent = true;
716
- this.disallowTransferToPeers = true;
717
- }
718
- if (this.subAgents && this.subAgents.length > 0) {
719
- throw new Error(
720
- "Invalid config for agent ".concat(this.name, ": if outputSchema is set, subAgents must be empty to disable agent transfer.")
721
- );
722
- }
723
- if (this.tools && this.tools.length > 0) {
724
- throw new Error(
725
- "Invalid config for agent ".concat(this.name, ": if outputSchema is set, tools must be empty")
726
- );
727
- }
728
- }
729
- }
730
- /**
731
- * The resolved BaseLlm instance.
732
- *
733
- * When not set, the agent will inherit the model from its ancestor.
734
- */
735
- get canonicalModel() {
736
- if (isBaseLlm(this.model)) {
737
- return this.model;
738
- }
739
- if (typeof this.model === "string" && this.model) {
740
- return LLMRegistry.newLlm(this.model);
741
- }
742
- let ancestorAgent = this.parentAgent;
743
- while (ancestorAgent) {
744
- if (ancestorAgent instanceof LlmAgent) {
745
- return ancestorAgent.canonicalModel;
746
- }
747
- ancestorAgent = ancestorAgent.parentAgent;
748
- }
749
- throw new Error("No model found for ".concat(this.name, "."));
750
- }
751
- /**
752
- * The resolved self.instruction field to construct instruction for this
753
- * agent.
754
- *
755
- * This method is only for use by Agent Development Kit.
756
- * @param context The context to retrieve the session state.
757
- * @returns The resolved self.instruction field.
758
- */
759
- async canonicalInstruction(context) {
760
- if (typeof this.instruction === "string") {
761
- return { instruction: this.instruction, requireStateInjection: true };
762
- }
763
- return {
764
- instruction: await this.instruction(context),
765
- requireStateInjection: false
766
- };
767
- }
768
- /**
769
- * The resolved self.instruction field to construct global instruction.
770
- *
771
- * This method is only for use by Agent Development Kit.
772
- * @param context The context to retrieve the session state.
773
- * @returns The resolved self.global_instruction field.
774
- */
775
- async canonicalGlobalInstruction(context) {
776
- if (typeof this.globalInstruction === "string") {
777
- return { instruction: this.globalInstruction, requireStateInjection: true };
778
- }
779
- return {
780
- instruction: await this.globalInstruction(context),
781
- requireStateInjection: false
782
- };
783
- }
784
- /**
785
- * The resolved self.tools field as a list of BaseTool based on the context.
786
- *
787
- * This method is only for use by Agent Development Kit.
788
- */
789
- async canonicalTools(context) {
790
- const resolvedTools = [];
791
- for (const toolUnion of this.tools) {
792
- const tools = await convertToolUnionToTools(toolUnion, context);
793
- resolvedTools.push(...tools);
794
- }
795
- return resolvedTools;
796
- }
797
- /**
798
- * Normalizes a callback or an array of callbacks into an array of callbacks.
799
- *
800
- * @param callback The callback or an array of callbacks.
801
- * @returns An array of callbacks.
802
- */
803
- static normalizeCallbackArray(callback) {
804
- if (!callback) {
805
- return [];
806
- }
807
- if (Array.isArray(callback)) {
808
- return callback;
809
- }
810
- return [callback];
811
- }
812
- /**
813
- * The resolved self.before_model_callback field as a list of
814
- * SingleBeforeModelCallback.
815
- *
816
- * This method is only for use by Agent Development Kit.
817
- */
818
- get canonicalBeforeModelCallbacks() {
819
- return LlmAgent.normalizeCallbackArray(this.beforeModelCallback);
820
- }
821
- /**
822
- * The resolved self.after_model_callback field as a list of
823
- * SingleAfterModelCallback.
824
- *
825
- * This method is only for use by Agent Development Kit.
826
- */
827
- get canonicalAfterModelCallbacks() {
828
- return LlmAgent.normalizeCallbackArray(this.afterModelCallback);
829
- }
830
- /**
831
- * The resolved self.before_tool_callback field as a list of
832
- * BeforeToolCallback.
833
- *
834
- * This method is only for use by Agent Development Kit.
835
- */
836
- get canonicalBeforeToolCallbacks() {
837
- return LlmAgent.normalizeCallbackArray(this.beforeToolCallback);
838
- }
839
- /**
840
- * The resolved self.after_tool_callback field as a list of AfterToolCallback.
841
- *
842
- * This method is only for use by Agent Development Kit.
843
- */
844
- get canonicalAfterToolCallbacks() {
845
- return LlmAgent.normalizeCallbackArray(this.afterToolCallback);
846
- }
847
- /**
848
- * Saves the agent's final response to the session state if configured.
849
- *
850
- * It extracts the text content from the final response event, optionally
851
- * parses it as JSON based on the output schema, and stores the result in the
852
- * session state using the specified output key.
853
- *
854
- * @param event The event to process.
855
- */
856
- maybeSaveOutputToState(event) {
857
- var _a, _b;
858
- if (event.author !== this.name) {
859
- logger.debug(
860
- "Skipping output save for agent ".concat(this.name, ": event authored by ").concat(event.author)
861
- );
862
- return;
863
- }
864
- if (!this.outputKey) {
865
- logger.debug(
866
- "Skipping output save for agent ".concat(this.name, ": outputKey is not set")
867
- );
868
- return;
869
- }
870
- if (!isFinalResponse(event)) {
871
- logger.debug(
872
- "Skipping output save for agent ".concat(this.name, ": event is not a final response")
873
- );
874
- return;
875
- }
876
- if (!((_b = (_a = event.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.length)) {
877
- logger.debug(
878
- "Skipping output save for agent ".concat(this.name, ": event content is empty")
879
- );
880
- return;
881
- }
882
- const resultStr = event.content.parts.map((part) => part.text ? part.text : "").join("");
883
- let result = resultStr;
884
- if (this.outputSchema) {
885
- if (!resultStr.trim()) {
886
- return;
887
- }
888
- try {
889
- result = JSON.parse(resultStr);
890
- } catch (e) {
891
- logger.error("Error parsing output for agent ".concat(this.name), e);
892
- }
893
- }
894
- event.actions.stateDelta[this.outputKey] = result;
895
- }
896
- runAsyncImpl(context) {
897
- return __asyncGenerator(this, null, function* () {
898
- while (true) {
899
- let lastEvent = void 0;
900
- try {
901
- for (var iter = __forAwait(this.runOneStepAsync(context)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
902
- const event = temp.value;
903
- lastEvent = event;
904
- this.maybeSaveOutputToState(event);
905
- yield event;
906
- }
907
- } catch (temp) {
908
- error = [temp];
909
- } finally {
910
- try {
911
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
912
- } finally {
913
- if (error)
914
- throw error[0];
915
- }
916
- }
917
- if (!lastEvent || isFinalResponse(lastEvent)) {
918
- break;
919
- }
920
- if (lastEvent.partial) {
921
- logger.warn("The last event is partial, which is not expected.");
922
- break;
923
- }
924
- }
925
- });
926
- }
927
- runLiveImpl(context) {
928
- return __asyncGenerator(this, null, function* () {
929
- try {
930
- for (var iter = __forAwait(this.runLiveFlow(context)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
931
- const event = temp.value;
932
- this.maybeSaveOutputToState(event);
933
- yield event;
934
- }
935
- } catch (temp) {
936
- error = [temp];
937
- } finally {
938
- try {
939
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
940
- } finally {
941
- if (error)
942
- throw error[0];
943
- }
944
- }
945
- if (context.endInvocation) {
946
- return;
947
- }
948
- });
949
- }
950
- // --------------------------------------------------------------------------
951
- // #START LlmFlow Logic
952
- // --------------------------------------------------------------------------
953
- runLiveFlow(invocationContext) {
954
- return __asyncGenerator(this, null, function* () {
955
- yield new __await(Promise.resolve());
956
- throw new Error("LlmAgent.runLiveFlow not implemented");
957
- });
958
- }
959
- runOneStepAsync(invocationContext) {
960
- return __asyncGenerator(this, null, function* () {
961
- const llmRequest = {
962
- contents: [],
963
- toolsDict: {},
964
- liveConnectConfig: {}
965
- };
966
- for (const processor of this.requestProcessors) {
967
- try {
968
- for (var iter = __forAwait(processor.runAsync(invocationContext, llmRequest)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
969
- const event = temp.value;
970
- yield event;
971
- }
972
- } catch (temp) {
973
- error = [temp];
974
- } finally {
975
- try {
976
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
977
- } finally {
978
- if (error)
979
- throw error[0];
980
- }
981
- }
982
- }
983
- for (const toolUnion of this.tools) {
984
- const toolContext = new ToolContext({ invocationContext });
985
- const tools = yield new __await(convertToolUnionToTools(
986
- toolUnion,
987
- new ReadonlyContext(invocationContext)
988
- ));
989
- for (const tool of tools) {
990
- yield new __await(tool.processLlmRequest({ toolContext, llmRequest }));
991
- }
992
- }
993
- if (invocationContext.endInvocation) {
994
- return;
995
- }
996
- const modelResponseEvent = createEvent({
997
- invocationId: invocationContext.invocationId,
998
- author: this.name,
999
- branch: invocationContext.branch
1000
- });
1001
- try {
1002
- for (var iter3 = __forAwait(this.callLlmAsync(
1003
- invocationContext,
1004
- llmRequest,
1005
- modelResponseEvent
1006
- )), more3, temp3, error3; more3 = !(temp3 = yield new __await(iter3.next())).done; more3 = false) {
1007
- const llmResponse = temp3.value;
1008
- try {
1009
- for (var iter2 = __forAwait(this.postprocess(
1010
- invocationContext,
1011
- llmRequest,
1012
- llmResponse,
1013
- modelResponseEvent
1014
- )), more2, temp2, error2; more2 = !(temp2 = yield new __await(iter2.next())).done; more2 = false) {
1015
- const event = temp2.value;
1016
- modelResponseEvent.id = createNewEventId();
1017
- modelResponseEvent.timestamp = (/* @__PURE__ */ new Date()).getTime();
1018
- yield event;
1019
- }
1020
- } catch (temp2) {
1021
- error2 = [temp2];
1022
- } finally {
1023
- try {
1024
- more2 && (temp2 = iter2.return) && (yield new __await(temp2.call(iter2)));
1025
- } finally {
1026
- if (error2)
1027
- throw error2[0];
1028
- }
1029
- }
1030
- }
1031
- } catch (temp3) {
1032
- error3 = [temp3];
1033
- } finally {
1034
- try {
1035
- more3 && (temp3 = iter3.return) && (yield new __await(temp3.call(iter3)));
1036
- } finally {
1037
- if (error3)
1038
- throw error3[0];
1039
- }
1040
- }
1041
- });
1042
- }
1043
- postprocess(invocationContext, llmRequest, llmResponse, modelResponseEvent) {
1044
- return __asyncGenerator(this, null, function* () {
1045
- var _a, _b, _c, _d, _e;
1046
- for (const processor of this.responseProcessors) {
1047
- try {
1048
- for (var iter = __forAwait(processor.runAsync(invocationContext, llmResponse)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
1049
- const event = temp.value;
1050
- yield event;
1051
- }
1052
- } catch (temp) {
1053
- error = [temp];
1054
- } finally {
1055
- try {
1056
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
1057
- } finally {
1058
- if (error)
1059
- throw error[0];
1060
- }
1061
- }
1062
- }
1063
- if (!llmResponse.content && !llmResponse.errorCode && !llmResponse.interrupted) {
1064
- return;
1065
- }
1066
- const mergedEvent = createEvent(__spreadValues(__spreadValues({}, modelResponseEvent), llmResponse));
1067
- if (mergedEvent.content) {
1068
- const functionCalls = getFunctionCalls(mergedEvent);
1069
- if (functionCalls == null ? void 0 : functionCalls.length) {
1070
- populateClientFunctionCallId(mergedEvent);
1071
- mergedEvent.longRunningToolIds = Array.from(
1072
- getLongRunningFunctionCalls(functionCalls, llmRequest.toolsDict)
1073
- );
1074
- const hasThought = (_a = mergedEvent.content.parts) == null ? void 0 : _a.some((p) => p.thought);
1075
- const hasSignature = (_b = mergedEvent.content.parts) == null ? void 0 : _b.some(
1076
- (p) => p.thoughtSignature
1077
- );
1078
- logger.info(
1079
- "[postprocess] Function call event: ".concat(functionCalls.length, " calls, ") + "hasThought=".concat(hasThought, ", hasSignature=").concat(hasSignature)
1080
- );
1081
- for (let i = 0; i < (((_c = mergedEvent.content.parts) == null ? void 0 : _c.length) || 0); i++) {
1082
- const part = mergedEvent.content.parts[i];
1083
- if (part.functionCall || part.thought) {
1084
- logger.info(
1085
- "[postprocess] Part ".concat(i, ": thought=").concat(!!part.thought, ", ") + "functionCall=".concat(((_d = part.functionCall) == null ? void 0 : _d.name) || "none", ", ") + "hasSignature=".concat(!!part.thoughtSignature)
1086
- );
1087
- }
1088
- }
1089
- if (!hasSignature) {
1090
- logger.warn(
1091
- "[postprocess] WARNING: Event has function calls but NO thoughtSignature! This will cause 400 errors when this content is sent back to Gemini 3."
1092
- );
1093
- }
1094
- }
1095
- }
1096
- yield mergedEvent;
1097
- if (!((_e = getFunctionCalls(mergedEvent)) == null ? void 0 : _e.length)) {
1098
- return;
1099
- }
1100
- const functionResponseEvent = yield new __await(handleFunctionCallsAsync({
1101
- invocationContext,
1102
- functionCallEvent: mergedEvent,
1103
- toolsDict: llmRequest.toolsDict,
1104
- beforeToolCallbacks: this.canonicalBeforeToolCallbacks,
1105
- afterToolCallbacks: this.canonicalAfterToolCallbacks
1106
- }));
1107
- if (!functionResponseEvent) {
1108
- return;
1109
- }
1110
- const authEvent = generateAuthEvent(invocationContext, functionResponseEvent);
1111
- if (authEvent) {
1112
- yield authEvent;
1113
- }
1114
- const toolConfirmationEvent = generateRequestConfirmationEvent({
1115
- invocationContext,
1116
- functionCallEvent: mergedEvent,
1117
- functionResponseEvent
1118
- });
1119
- if (toolConfirmationEvent) {
1120
- yield toolConfirmationEvent;
1121
- }
1122
- yield functionResponseEvent;
1123
- const nextAgentName = functionResponseEvent.actions.transferToAgent;
1124
- if (nextAgentName) {
1125
- const nextAgent = this.getAgentByName(invocationContext, nextAgentName);
1126
- try {
1127
- for (var iter2 = __forAwait(nextAgent.runAsync(invocationContext)), more2, temp2, error2; more2 = !(temp2 = yield new __await(iter2.next())).done; more2 = false) {
1128
- const event = temp2.value;
1129
- yield event;
1130
- }
1131
- } catch (temp2) {
1132
- error2 = [temp2];
1133
- } finally {
1134
- try {
1135
- more2 && (temp2 = iter2.return) && (yield new __await(temp2.call(iter2)));
1136
- } finally {
1137
- if (error2)
1138
- throw error2[0];
1139
- }
1140
- }
1141
- }
1142
- });
1143
- }
1144
- /**
1145
- * Retrieves an agent from the agent tree by its name.
1146
- *
1147
- * Performing a depth-first search to locate the agent with the given name.
1148
- * - Starts searching from the root agent of the current invocation context.
1149
- * - Traverses down the agent tree to find the specified agent.
1150
- *
1151
- * @param invocationContext The current invocation context.
1152
- * @param agentName The name of the agent to retrieve.
1153
- * @returns The agent with the given name.
1154
- * @throws Error if the agent is not found.
1155
- */
1156
- getAgentByName(invocationContext, agentName) {
1157
- const rootAgent = invocationContext.agent.rootAgent;
1158
- const agentToRun = rootAgent.findAgent(agentName);
1159
- if (!agentToRun) {
1160
- throw new Error("Agent ".concat(agentName, " not found in the agent tree."));
1161
- }
1162
- return agentToRun;
1163
- }
1164
- callLlmAsync(invocationContext, llmRequest, modelResponseEvent) {
1165
- return __asyncGenerator(this, null, function* () {
1166
- var _a, _b, _c, _d, _e;
1167
- const beforeModelResponse = yield new __await(this.handleBeforeModelCallback(
1168
- invocationContext,
1169
- llmRequest,
1170
- modelResponseEvent
1171
- ));
1172
- if (beforeModelResponse) {
1173
- yield beforeModelResponse;
1174
- return;
1175
- }
1176
- (_a = llmRequest.config) != null ? _a : llmRequest.config = {};
1177
- (_c = (_b = llmRequest.config).labels) != null ? _c : _b.labels = {};
1178
- if (!llmRequest.config.labels[ADK_AGENT_NAME_LABEL_KEY]) {
1179
- llmRequest.config.labels[ADK_AGENT_NAME_LABEL_KEY] = this.name;
1180
- }
1181
- const llm = this.canonicalModel;
1182
- if ((_d = invocationContext.runConfig) == null ? void 0 : _d.supportCfc) {
1183
- throw new Error("CFC is not yet supported in callLlmAsync");
1184
- } else {
1185
- invocationContext.incrementLlmCallCount();
1186
- const responsesGenerator = llm.generateContentAsync(
1187
- llmRequest,
1188
- /* stream= */
1189
- ((_e = invocationContext.runConfig) == null ? void 0 : _e.streamingMode) === StreamingMode.SSE
1190
- );
1191
- try {
1192
- for (var iter = __forAwait(this.runAndHandleError(
1193
- responsesGenerator,
1194
- invocationContext,
1195
- llmRequest,
1196
- modelResponseEvent
1197
- )), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
1198
- const llmResponse = temp.value;
1199
- const alteredLlmResponse = yield new __await(this.handleAfterModelCallback(
1200
- invocationContext,
1201
- llmResponse,
1202
- modelResponseEvent
1203
- ));
1204
- yield alteredLlmResponse != null ? alteredLlmResponse : llmResponse;
1205
- }
1206
- } catch (temp) {
1207
- error = [temp];
1208
- } finally {
1209
- try {
1210
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
1211
- } finally {
1212
- if (error)
1213
- throw error[0];
1214
- }
1215
- }
1216
- }
1217
- });
1218
- }
1219
- async handleBeforeModelCallback(invocationContext, llmRequest, modelResponseEvent) {
1220
- const callbackContext = new CallbackContext(
1221
- { invocationContext, eventActions: modelResponseEvent.actions }
1222
- );
1223
- const beforeModelCallbackResponse = await invocationContext.pluginManager.runBeforeModelCallback(
1224
- { callbackContext, llmRequest }
1225
- );
1226
- if (beforeModelCallbackResponse) {
1227
- return beforeModelCallbackResponse;
1228
- }
1229
- for (const callback of this.canonicalBeforeModelCallbacks) {
1230
- const callbackResponse = await callback({ context: callbackContext, request: llmRequest });
1231
- if (callbackResponse) {
1232
- return callbackResponse;
1233
- }
1234
- }
1235
- return void 0;
1236
- }
1237
- async handleAfterModelCallback(invocationContext, llmResponse, modelResponseEvent) {
1238
- const callbackContext = new CallbackContext(
1239
- { invocationContext, eventActions: modelResponseEvent.actions }
1240
- );
1241
- const afterModelCallbackResponse = await invocationContext.pluginManager.runAfterModelCallback(
1242
- { callbackContext, llmResponse }
1243
- );
1244
- if (afterModelCallbackResponse) {
1245
- return afterModelCallbackResponse;
1246
- }
1247
- for (const callback of this.canonicalAfterModelCallbacks) {
1248
- const callbackResponse = await callback({ context: callbackContext, response: llmResponse });
1249
- if (callbackResponse) {
1250
- return callbackResponse;
1251
- }
1252
- }
1253
- return void 0;
1254
- }
1255
- runAndHandleError(responseGenerator, invocationContext, llmRequest, modelResponseEvent) {
1256
- return __asyncGenerator(this, null, function* () {
1257
- try {
1258
- try {
1259
- for (var iter = __forAwait(responseGenerator), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
1260
- const response = temp.value;
1261
- yield response;
1262
- }
1263
- } catch (temp) {
1264
- error = [temp];
1265
- } finally {
1266
- try {
1267
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
1268
- } finally {
1269
- if (error)
1270
- throw error[0];
1271
- }
1272
- }
1273
- } catch (modelError) {
1274
- const callbackContext = new CallbackContext(
1275
- { invocationContext, eventActions: modelResponseEvent.actions }
1276
- );
1277
- if (modelError instanceof Error) {
1278
- const onModelErrorCallbackResponse = yield new __await(invocationContext.pluginManager.runOnModelErrorCallback({
1279
- callbackContext,
1280
- llmRequest,
1281
- error: modelError
1282
- }));
1283
- if (onModelErrorCallbackResponse) {
1284
- yield onModelErrorCallbackResponse;
1285
- } else {
1286
- const errorResponse = JSON.parse(modelError.message);
1287
- yield {
1288
- errorCode: String(errorResponse.error.code),
1289
- errorMessage: errorResponse.error.message
1290
- };
1291
- }
1292
- } else {
1293
- logger.error("Unknown error during response generation", modelError);
1294
- throw modelError;
1295
- }
1296
- }
1297
- });
1298
- }
1299
- // --------------------------------------------------------------------------
1300
- // #END LlmFlow Logic
1301
- // --------------------------------------------------------------------------
1302
- // TODO - b/425992518: omitted Py LlmAgent features.
1303
- // - code_executor
1304
- // - configurable agents by yaml config
1305
- }
1306
- export {
1307
- LlmAgent,
1308
- REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
1309
- responseProcessor
1310
- };