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