@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
@@ -69,40 +69,17 @@ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")])
69
69
  */
70
70
  var _a, _b;
71
71
  import { context, trace } from "@opentelemetry/api";
72
- import { cloneDeep } from "lodash-es";
73
- import { z } from "zod";
74
- import {
75
- isBaseCodeExecutor
76
- } from "../code_executors/base_code_executor.js";
77
- import { isBuiltInCodeExecutor } from "../code_executors/built_in_code_executor.js";
78
- import {
79
- buildCodeExecutionResultPart,
80
- buildExecutableCodePart,
81
- convertCodeExecutionParts,
82
- extractCodeAndTruncateContent
83
- } from "../code_executors/code_execution_utils.js";
84
- import { CodeExecutorContext } from "../code_executors/code_executor_context.js";
85
72
  import {
86
73
  createEvent,
87
74
  createNewEventId,
88
75
  getFunctionCalls,
89
- getFunctionResponses,
90
76
  isFinalResponse
91
77
  } from "../events/event.js";
92
- import { createEventActions } from "../events/event_actions.js";
93
78
  import { isBaseLlm } from "../models/base_llm.js";
94
- import {
95
- appendInstructions,
96
- setOutputSchema
97
- } from "../models/llm_request.js";
98
79
  import { LLMRegistry } from "../models/registry.js";
99
- import { State } from "../sessions/state.js";
100
80
  import { isBaseTool } from "../tools/base_tool.js";
101
- import { FunctionTool } from "../tools/function_tool.js";
102
- import { ToolConfirmation } from "../tools/tool_confirmation.js";
103
- import { ToolContext } from "../tools/tool_context.js";
104
- import { base64Decode } from "../utils/env_aware_utils.js";
105
81
  import { logger } from "../utils/logger.js";
82
+ import { Context } from "./context.js";
106
83
  import {
107
84
  runAsyncGeneratorWithOtelContext,
108
85
  traceCallLlm,
@@ -110,24 +87,20 @@ import {
110
87
  } from "../telemetry/tracing.js";
111
88
  import { isZodObject, zodObjectToSchema } from "../utils/simple_zod_to_json.js";
112
89
  import { BaseAgent } from "./base_agent.js";
113
- import {
114
- BaseLlmRequestProcessor
115
- } from "./base_llm_processor.js";
116
- import { CallbackContext } from "./callback_context.js";
117
- import {
118
- getContents,
119
- getCurrentTurnContents
120
- } from "./content_processor_utils.js";
121
90
  import {
122
91
  generateAuthEvent,
123
92
  generateRequestConfirmationEvent,
124
93
  getLongRunningFunctionCalls,
125
- handleFunctionCallList,
126
94
  handleFunctionCallsAsync,
127
- populateClientFunctionCallId,
128
- REQUEST_CONFIRMATION_FUNCTION_CALL_NAME
95
+ populateClientFunctionCallId
129
96
  } from "./functions.js";
130
- import { injectSessionState } from "./instructions.js";
97
+ import { AGENT_TRANSFER_LLM_REQUEST_PROCESSOR } from "./processors/agent_transfer_llm_request_processor.js";
98
+ import { BASIC_LLM_REQUEST_PROCESSOR } from "./processors/basic_llm_request_processor.js";
99
+ import { CODE_EXECUTION_REQUEST_PROCESSOR } from "./processors/code_execution_request_processor.js";
100
+ import { CONTENT_REQUEST_PROCESSOR } from "./processors/content_request_processor.js";
101
+ import { IDENTITY_LLM_REQUEST_PROCESSOR } from "./processors/identity_llm_request_processor.js";
102
+ import { INSTRUCTIONS_LLM_REQUEST_PROCESSOR } from "./processors/instructions_llm_request_processor.js";
103
+ import { REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR } from "./processors/request_confirmation_llm_request_processor.js";
131
104
  import { ReadonlyContext } from "./readonly_context.js";
132
105
  import { StreamingMode } from "./run_config.js";
133
106
  const ADK_AGENT_NAME_LABEL_KEY = "adk_agent_name";
@@ -137,624 +110,6 @@ async function convertToolUnionToTools(toolUnion, context2) {
137
110
  }
138
111
  return await toolUnion.getTools(context2);
139
112
  }
140
- class BasicLlmRequestProcessor extends BaseLlmRequestProcessor {
141
- // eslint-disable-next-line require-yield
142
- runAsync(invocationContext, llmRequest) {
143
- return __asyncGenerator(this, null, function* () {
144
- var _a2;
145
- const agent = invocationContext.agent;
146
- if (!isLlmAgent(agent)) {
147
- return;
148
- }
149
- llmRequest.model = agent.canonicalModel.model;
150
- llmRequest.config = __spreadValues({}, (_a2 = agent.generateContentConfig) != null ? _a2 : {});
151
- if (agent.outputSchema) {
152
- setOutputSchema(llmRequest, agent.outputSchema);
153
- }
154
- if (invocationContext.runConfig) {
155
- llmRequest.liveConnectConfig.responseModalities = invocationContext.runConfig.responseModalities;
156
- llmRequest.liveConnectConfig.speechConfig = invocationContext.runConfig.speechConfig;
157
- llmRequest.liveConnectConfig.outputAudioTranscription = invocationContext.runConfig.outputAudioTranscription;
158
- llmRequest.liveConnectConfig.inputAudioTranscription = invocationContext.runConfig.inputAudioTranscription;
159
- llmRequest.liveConnectConfig.realtimeInputConfig = invocationContext.runConfig.realtimeInputConfig;
160
- llmRequest.liveConnectConfig.enableAffectiveDialog = invocationContext.runConfig.enableAffectiveDialog;
161
- llmRequest.liveConnectConfig.proactivity = invocationContext.runConfig.proactivity;
162
- }
163
- });
164
- }
165
- }
166
- const BASIC_LLM_REQUEST_PROCESSOR = new BasicLlmRequestProcessor();
167
- class IdentityLlmRequestProcessor extends BaseLlmRequestProcessor {
168
- // eslint-disable-next-line require-yield
169
- runAsync(invocationContext, llmRequest) {
170
- return __asyncGenerator(this, null, function* () {
171
- const agent = invocationContext.agent;
172
- const si = ['You are an agent. Your internal name is "'.concat(agent.name, '".')];
173
- if (agent.description) {
174
- si.push('The description about you is "'.concat(agent.description, '"'));
175
- }
176
- appendInstructions(llmRequest, si);
177
- });
178
- }
179
- }
180
- const IDENTITY_LLM_REQUEST_PROCESSOR = new IdentityLlmRequestProcessor();
181
- class InstructionsLlmRequestProcessor extends BaseLlmRequestProcessor {
182
- /**
183
- * Handles instructions and global instructions for LLM flow.
184
- */
185
- // eslint-disable-next-line require-yield
186
- runAsync(invocationContext, llmRequest) {
187
- return __asyncGenerator(this, null, function* () {
188
- const agent = invocationContext.agent;
189
- if (!isLlmAgent(agent) || !isLlmAgent(agent.rootAgent)) {
190
- return;
191
- }
192
- const rootAgent = agent.rootAgent;
193
- if (isLlmAgent(rootAgent) && rootAgent.globalInstruction) {
194
- const { instruction, requireStateInjection } = yield new __await(rootAgent.canonicalGlobalInstruction(
195
- new ReadonlyContext(invocationContext)
196
- ));
197
- let instructionWithState = instruction;
198
- if (requireStateInjection) {
199
- instructionWithState = yield new __await(injectSessionState(
200
- instruction,
201
- new ReadonlyContext(invocationContext)
202
- ));
203
- }
204
- appendInstructions(llmRequest, [instructionWithState]);
205
- }
206
- if (agent.instruction) {
207
- const { instruction, requireStateInjection } = yield new __await(agent.canonicalInstruction(
208
- new ReadonlyContext(invocationContext)
209
- ));
210
- let instructionWithState = instruction;
211
- if (requireStateInjection) {
212
- instructionWithState = yield new __await(injectSessionState(
213
- instruction,
214
- new ReadonlyContext(invocationContext)
215
- ));
216
- }
217
- appendInstructions(llmRequest, [instructionWithState]);
218
- }
219
- });
220
- }
221
- }
222
- const INSTRUCTIONS_LLM_REQUEST_PROCESSOR = new InstructionsLlmRequestProcessor();
223
- class ContentRequestProcessor {
224
- // eslint-disable-next-line require-yield
225
- runAsync(invocationContext, llmRequest) {
226
- return __asyncGenerator(this, null, function* () {
227
- const agent = invocationContext.agent;
228
- if (!agent || !isLlmAgent(agent)) {
229
- return;
230
- }
231
- if (agent.includeContents === "default") {
232
- llmRequest.contents = getContents(
233
- invocationContext.session.events,
234
- agent.name,
235
- invocationContext.branch
236
- );
237
- } else {
238
- llmRequest.contents = getCurrentTurnContents(
239
- invocationContext.session.events,
240
- agent.name,
241
- invocationContext.branch
242
- );
243
- }
244
- return;
245
- });
246
- }
247
- }
248
- const CONTENT_REQUEST_PROCESSOR = new ContentRequestProcessor();
249
- class AgentTransferLlmRequestProcessor extends BaseLlmRequestProcessor {
250
- constructor() {
251
- super(...arguments);
252
- this.toolName = "transfer_to_agent";
253
- this.tool = new FunctionTool({
254
- name: this.toolName,
255
- 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.",
256
- parameters: z.object({
257
- agentName: z.string().describe("the agent name to transfer to.")
258
- }),
259
- execute: function(args, toolContext) {
260
- if (!toolContext) {
261
- throw new Error("toolContext is required.");
262
- }
263
- toolContext.actions.transferToAgent = args.agentName;
264
- return "Transfer queued";
265
- }
266
- });
267
- }
268
- // eslint-disable-next-line require-yield
269
- runAsync(invocationContext, llmRequest) {
270
- return __asyncGenerator(this, null, function* () {
271
- if (!isLlmAgent(invocationContext.agent)) {
272
- return;
273
- }
274
- const transferTargets = this.getTransferTargets(invocationContext.agent);
275
- if (!transferTargets.length) {
276
- return;
277
- }
278
- appendInstructions(llmRequest, [
279
- this.buildTargetAgentsInstructions(
280
- invocationContext.agent,
281
- transferTargets
282
- )
283
- ]);
284
- const toolContext = new ToolContext({ invocationContext });
285
- yield new __await(this.tool.processLlmRequest({ toolContext, llmRequest }));
286
- });
287
- }
288
- buildTargetAgentsInfo(targetAgent) {
289
- return "\nAgent name: ".concat(targetAgent.name, "\nAgent description: ").concat(targetAgent.description, "\n");
290
- }
291
- buildTargetAgentsInstructions(agent, targetAgents) {
292
- 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");
293
- if (agent.parentAgent && !agent.disallowTransferToParent) {
294
- 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");
295
- }
296
- return instructions;
297
- }
298
- getTransferTargets(agent) {
299
- const targets = [];
300
- targets.push(...agent.subAgents);
301
- if (!agent.parentAgent || !isLlmAgent(agent.parentAgent)) {
302
- return targets;
303
- }
304
- if (!agent.disallowTransferToParent) {
305
- targets.push(agent.parentAgent);
306
- }
307
- if (!agent.disallowTransferToPeers) {
308
- targets.push(
309
- ...agent.parentAgent.subAgents.filter(
310
- (peerAgent) => peerAgent.name !== agent.name
311
- )
312
- );
313
- }
314
- return targets;
315
- }
316
- }
317
- const AGENT_TRANSFER_LLM_REQUEST_PROCESSOR = new AgentTransferLlmRequestProcessor();
318
- class RequestConfirmationLlmRequestProcessor extends BaseLlmRequestProcessor {
319
- /** Handles tool confirmation information to build the LLM request. */
320
- runAsync(invocationContext) {
321
- return __asyncGenerator(this, null, function* () {
322
- const agent = invocationContext.agent;
323
- if (!isLlmAgent(agent)) {
324
- return;
325
- }
326
- const events = invocationContext.session.events;
327
- if (!events || events.length === 0) {
328
- return;
329
- }
330
- const requestConfirmationFunctionResponses = {};
331
- let confirmationEventIndex = -1;
332
- for (let i = events.length - 1; i >= 0; i--) {
333
- const event = events[i];
334
- if (event.author !== "user") {
335
- continue;
336
- }
337
- const responses = getFunctionResponses(event);
338
- if (!responses) {
339
- continue;
340
- }
341
- let foundConfirmation = false;
342
- for (const functionResponse of responses) {
343
- if (functionResponse.name !== REQUEST_CONFIRMATION_FUNCTION_CALL_NAME) {
344
- continue;
345
- }
346
- foundConfirmation = true;
347
- let toolConfirmation = null;
348
- if (functionResponse.response && Object.keys(functionResponse.response).length === 1 && "response" in functionResponse.response) {
349
- toolConfirmation = JSON.parse(
350
- functionResponse.response["response"]
351
- );
352
- } else if (functionResponse.response) {
353
- toolConfirmation = new ToolConfirmation({
354
- hint: functionResponse.response["hint"],
355
- payload: functionResponse.response["payload"],
356
- confirmed: functionResponse.response["confirmed"]
357
- });
358
- }
359
- if (functionResponse.id && toolConfirmation) {
360
- requestConfirmationFunctionResponses[functionResponse.id] = toolConfirmation;
361
- }
362
- }
363
- if (foundConfirmation) {
364
- confirmationEventIndex = i;
365
- break;
366
- }
367
- }
368
- if (Object.keys(requestConfirmationFunctionResponses).length === 0) {
369
- return;
370
- }
371
- for (let i = confirmationEventIndex - 1; i >= 0; i--) {
372
- const event = events[i];
373
- const functionCalls = getFunctionCalls(event);
374
- if (!functionCalls) {
375
- continue;
376
- }
377
- const toolsToResumeWithConfirmation = {};
378
- const toolsToResumeWithArgs = {};
379
- for (const functionCall of functionCalls) {
380
- if (!functionCall.id || !(functionCall.id in requestConfirmationFunctionResponses)) {
381
- continue;
382
- }
383
- const args = functionCall.args;
384
- if (!args || !("originalFunctionCall" in args)) {
385
- continue;
386
- }
387
- const originalFunctionCall = args["originalFunctionCall"];
388
- if (originalFunctionCall.id) {
389
- toolsToResumeWithConfirmation[originalFunctionCall.id] = requestConfirmationFunctionResponses[functionCall.id];
390
- toolsToResumeWithArgs[originalFunctionCall.id] = originalFunctionCall;
391
- }
392
- }
393
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
394
- continue;
395
- }
396
- for (let j = events.length - 1; j > confirmationEventIndex; j--) {
397
- const eventToCheck = events[j];
398
- const functionResponses = getFunctionResponses(eventToCheck);
399
- if (!functionResponses) {
400
- continue;
401
- }
402
- for (const fr of functionResponses) {
403
- if (fr.id && fr.id in toolsToResumeWithConfirmation) {
404
- delete toolsToResumeWithConfirmation[fr.id];
405
- delete toolsToResumeWithArgs[fr.id];
406
- }
407
- }
408
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
409
- break;
410
- }
411
- }
412
- if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
413
- continue;
414
- }
415
- const toolsList = yield new __await(agent.canonicalTools(
416
- new ReadonlyContext(invocationContext)
417
- ));
418
- const toolsDict = Object.fromEntries(
419
- toolsList.map((tool) => [tool.name, tool])
420
- );
421
- const functionResponseEvent = yield new __await(handleFunctionCallList({
422
- invocationContext,
423
- functionCalls: Object.values(toolsToResumeWithArgs),
424
- toolsDict,
425
- beforeToolCallbacks: agent.canonicalBeforeToolCallbacks,
426
- afterToolCallbacks: agent.canonicalAfterToolCallbacks,
427
- filters: new Set(Object.keys(toolsToResumeWithConfirmation)),
428
- toolConfirmationDict: toolsToResumeWithConfirmation
429
- }));
430
- if (functionResponseEvent) {
431
- yield functionResponseEvent;
432
- }
433
- return;
434
- }
435
- });
436
- }
437
- }
438
- const REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR = new RequestConfirmationLlmRequestProcessor();
439
- class CodeExecutionRequestProcessor extends BaseLlmRequestProcessor {
440
- runAsync(invocationContext, llmRequest) {
441
- return __asyncGenerator(this, null, function* () {
442
- if (!isLlmAgent(invocationContext.agent)) {
443
- return;
444
- }
445
- if (!invocationContext.agent.codeExecutor) {
446
- return;
447
- }
448
- try {
449
- for (var iter = __forAwait(runPreProcessor(invocationContext, llmRequest)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
450
- const event = temp.value;
451
- yield event;
452
- }
453
- } catch (temp) {
454
- error = [temp];
455
- } finally {
456
- try {
457
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
458
- } finally {
459
- if (error)
460
- throw error[0];
461
- }
462
- }
463
- if (!isBaseCodeExecutor(invocationContext.agent.codeExecutor)) {
464
- return;
465
- }
466
- for (const content of llmRequest.contents) {
467
- const delimeters = invocationContext.agent.codeExecutor.codeBlockDelimiters.length ? invocationContext.agent.codeExecutor.codeBlockDelimiters[0] : ["", ""];
468
- convertCodeExecutionParts(
469
- content,
470
- delimeters,
471
- invocationContext.agent.codeExecutor.executionResultDelimiters
472
- );
473
- }
474
- });
475
- }
476
- }
477
- const DATA_FILE_UTIL_MAP = {
478
- "text/csv": {
479
- extension: ".csv",
480
- loaderCodeTemplate: "pd.read_csv('{filename}')"
481
- }
482
- };
483
- 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";
484
- class CodeExecutionResponseProcessor {
485
- /**
486
- * Processes the LLM response asynchronously.
487
- *
488
- * @param invocationContext The invocation context
489
- * @param llmResponse The LLM response to process
490
- * @returns An async generator yielding events
491
- */
492
- runAsync(invocationContext, llmResponse) {
493
- return __asyncGenerator(this, null, function* () {
494
- if (llmResponse.partial) {
495
- return;
496
- }
497
- try {
498
- for (var iter = __forAwait(runPostProcessor(
499
- invocationContext,
500
- llmResponse
501
- )), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
502
- const event = temp.value;
503
- yield event;
504
- }
505
- } catch (temp) {
506
- error = [temp];
507
- } finally {
508
- try {
509
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
510
- } finally {
511
- if (error)
512
- throw error[0];
513
- }
514
- }
515
- });
516
- }
517
- }
518
- const responseProcessor = new CodeExecutionResponseProcessor();
519
- function runPreProcessor(invocationContext, llmRequest) {
520
- return __asyncGenerator(this, null, function* () {
521
- const agent = invocationContext.agent;
522
- if (!isLlmAgent(agent)) {
523
- return;
524
- }
525
- const codeExecutor = agent.codeExecutor;
526
- if (!codeExecutor || !isBaseCodeExecutor(codeExecutor)) {
527
- return;
528
- }
529
- if (isBuiltInCodeExecutor(codeExecutor)) {
530
- codeExecutor.processLlmRequest(llmRequest);
531
- return;
532
- }
533
- if (!codeExecutor.optimizeDataFile) {
534
- return;
535
- }
536
- const codeExecutorContext = new CodeExecutorContext(
537
- new State(invocationContext.session.state)
538
- );
539
- if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
540
- return;
541
- }
542
- const allInputFiles = extractAndReplaceInlineFiles(
543
- codeExecutorContext,
544
- llmRequest
545
- );
546
- const processedFileNames = new Set(
547
- codeExecutorContext.getProcessedFileNames()
548
- );
549
- const filesToProcess = allInputFiles.filter(
550
- (f) => !processedFileNames.has(f.name)
551
- );
552
- for (const file of filesToProcess) {
553
- const codeStr = getDataFilePreprocessingCode(file);
554
- if (!codeStr) {
555
- return;
556
- }
557
- const codeContent = {
558
- role: "model",
559
- parts: [
560
- { text: "Processing input file: `".concat(file.name, "`") },
561
- buildExecutableCodePart(codeStr)
562
- ]
563
- };
564
- llmRequest.contents.push(cloneDeep(codeContent));
565
- yield createEvent({
566
- invocationId: invocationContext.invocationId,
567
- author: agent.name,
568
- branch: invocationContext.branch,
569
- content: codeContent
570
- });
571
- const executionId = getOrSetExecutionId(
572
- invocationContext,
573
- codeExecutorContext
574
- );
575
- const codeExecutionResult = yield new __await(codeExecutor.executeCode({
576
- invocationContext,
577
- codeExecutionInput: {
578
- code: codeStr,
579
- inputFiles: [file],
580
- executionId
581
- }
582
- }));
583
- codeExecutorContext.updateCodeExecutionResult({
584
- invocationId: invocationContext.invocationId,
585
- code: codeStr,
586
- resultStdout: codeExecutionResult.stdout,
587
- resultStderr: codeExecutionResult.stderr
588
- });
589
- codeExecutorContext.addProcessedFileNames([file.name]);
590
- const executionResultEvent = yield new __await(postProcessCodeExecutionResult(
591
- invocationContext,
592
- codeExecutorContext,
593
- codeExecutionResult
594
- ));
595
- yield executionResultEvent;
596
- llmRequest.contents.push(cloneDeep(executionResultEvent.content));
597
- }
598
- });
599
- }
600
- function runPostProcessor(invocationContext, llmResponse) {
601
- return __asyncGenerator(this, null, function* () {
602
- const agent = invocationContext.agent;
603
- if (!isLlmAgent(agent)) {
604
- return;
605
- }
606
- const codeExecutor = agent.codeExecutor;
607
- if (!codeExecutor || !isBaseCodeExecutor(codeExecutor)) {
608
- return;
609
- }
610
- if (!llmResponse || !llmResponse.content) {
611
- return;
612
- }
613
- if (isBuiltInCodeExecutor(codeExecutor)) {
614
- return;
615
- }
616
- const codeExecutorContext = new CodeExecutorContext(
617
- new State(invocationContext.session.state)
618
- );
619
- if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
620
- return;
621
- }
622
- const responseContent = llmResponse.content;
623
- const codeStr = extractCodeAndTruncateContent(
624
- responseContent,
625
- codeExecutor.codeBlockDelimiters
626
- );
627
- if (!codeStr) {
628
- return;
629
- }
630
- yield createEvent({
631
- invocationId: invocationContext.invocationId,
632
- author: agent.name,
633
- branch: invocationContext.branch,
634
- content: responseContent
635
- });
636
- const executionId = getOrSetExecutionId(
637
- invocationContext,
638
- codeExecutorContext
639
- );
640
- const codeExecutionResult = yield new __await(codeExecutor.executeCode({
641
- invocationContext,
642
- codeExecutionInput: {
643
- code: codeStr,
644
- inputFiles: codeExecutorContext.getInputFiles(),
645
- executionId
646
- }
647
- }));
648
- codeExecutorContext.updateCodeExecutionResult({
649
- invocationId: invocationContext.invocationId,
650
- code: codeStr,
651
- resultStdout: codeExecutionResult.stdout,
652
- resultStderr: codeExecutionResult.stderr
653
- });
654
- yield yield new __await(postProcessCodeExecutionResult(
655
- invocationContext,
656
- codeExecutorContext,
657
- codeExecutionResult
658
- ));
659
- llmResponse.content = void 0;
660
- });
661
- }
662
- function extractAndReplaceInlineFiles(codeExecutorContext, llmRequest) {
663
- var _a2;
664
- const allInputFiles = codeExecutorContext.getInputFiles();
665
- const savedFileNames = new Set(allInputFiles.map((f) => f.name));
666
- for (let i = 0; i < llmRequest.contents.length; i++) {
667
- const content = llmRequest.contents[i];
668
- if (content.role !== "user" || !content.parts) {
669
- continue;
670
- }
671
- for (let j = 0; j < content.parts.length; j++) {
672
- const part = content.parts[j];
673
- const mimeType = (_a2 = part.inlineData) == null ? void 0 : _a2.mimeType;
674
- if (!mimeType || !part.inlineData || !DATA_FILE_UTIL_MAP[mimeType]) {
675
- continue;
676
- }
677
- const fileName = "data_".concat(i + 1, "_").concat(j + 1).concat(DATA_FILE_UTIL_MAP[mimeType].extension);
678
- part.text = "\nAvailable file: `".concat(fileName, "`\n");
679
- const file = {
680
- name: fileName,
681
- content: base64Decode(part.inlineData.data),
682
- mimeType
683
- };
684
- if (!savedFileNames.has(fileName)) {
685
- codeExecutorContext.addInputFiles([file]);
686
- allInputFiles.push(file);
687
- }
688
- }
689
- }
690
- return allInputFiles;
691
- }
692
- function getOrSetExecutionId(invocationContext, codeExecutorContext) {
693
- var _a2;
694
- const agent = invocationContext.agent;
695
- if (!isLlmAgent(agent) || !((_a2 = agent.codeExecutor) == null ? void 0 : _a2.stateful)) {
696
- return void 0;
697
- }
698
- let executionId = codeExecutorContext.getExecutionId();
699
- if (!executionId) {
700
- executionId = invocationContext.session.id;
701
- codeExecutorContext.setExecutionId(executionId);
702
- }
703
- return executionId;
704
- }
705
- async function postProcessCodeExecutionResult(invocationContext, codeExecutorContext, codeExecutionResult) {
706
- if (!invocationContext.artifactService) {
707
- throw new Error("Artifact service is not initialized.");
708
- }
709
- const resultContent = {
710
- role: "model",
711
- parts: [buildCodeExecutionResultPart(codeExecutionResult)]
712
- };
713
- const eventActions = createEventActions({
714
- stateDelta: codeExecutorContext.getStateDelta()
715
- });
716
- if (codeExecutionResult.stderr) {
717
- codeExecutorContext.incrementErrorCount(invocationContext.invocationId);
718
- } else {
719
- codeExecutorContext.resetErrorCount(invocationContext.invocationId);
720
- }
721
- for (const outputFile of codeExecutionResult.outputFiles) {
722
- const version = await invocationContext.artifactService.saveArtifact({
723
- appName: invocationContext.appName || "",
724
- userId: invocationContext.userId || "",
725
- sessionId: invocationContext.session.id,
726
- filename: outputFile.name,
727
- artifact: {
728
- inlineData: { data: outputFile.content, mimeType: outputFile.mimeType }
729
- }
730
- });
731
- eventActions.artifactDelta[outputFile.name] = version;
732
- }
733
- return createEvent({
734
- invocationId: invocationContext.invocationId,
735
- author: invocationContext.agent.name,
736
- branch: invocationContext.branch,
737
- content: resultContent,
738
- actions: eventActions
739
- });
740
- }
741
- function getDataFilePreprocessingCode(file) {
742
- function getNormalizedFileName(fileName) {
743
- const [varName2] = fileName.split(".");
744
- let normalizedName = varName2.replace(/[^a-zA-Z0-9_]/g, "_");
745
- if (/^\d/.test(normalizedName)) {
746
- normalizedName = "_" + normalizedName;
747
- }
748
- return normalizedName;
749
- }
750
- if (!DATA_FILE_UTIL_MAP[file.mimeType]) {
751
- return void 0;
752
- }
753
- const varName = getNormalizedFileName(file.name);
754
- const loaderCode = DATA_FILE_UTIL_MAP[file.mimeType].loaderCodeTemplate.replace("{filename}", file.name);
755
- 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");
756
- }
757
- const CODE_EXECUTION_REQUEST_PROCESSOR = new CodeExecutionRequestProcessor();
758
113
  const LLM_AGENT_SIGNATURE_SYMBOL = Symbol.for("google.adk.llmAgent");
759
114
  function isLlmAgent(obj) {
760
115
  return typeof obj === "object" && obj !== null && LLM_AGENT_SIGNATURE_SYMBOL in obj && obj[LLM_AGENT_SIGNATURE_SYMBOL] === true;
@@ -1082,7 +437,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1082
437
  }
1083
438
  }
1084
439
  for (const toolUnion of this.tools) {
1085
- const toolContext = new ToolContext({ invocationContext });
440
+ const toolContext = new Context({ invocationContext });
1086
441
  const tools = yield new __await(convertToolUnionToTools(
1087
442
  toolUnion,
1088
443
  new ReadonlyContext(invocationContext)
@@ -1332,7 +687,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1332
687
  });
1333
688
  }
1334
689
  async handleBeforeModelCallback(invocationContext, llmRequest, modelResponseEvent) {
1335
- const callbackContext = new CallbackContext({
690
+ const callbackContext = new Context({
1336
691
  invocationContext,
1337
692
  eventActions: modelResponseEvent.actions
1338
693
  });
@@ -1355,7 +710,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1355
710
  return void 0;
1356
711
  }
1357
712
  async handleAfterModelCallback(invocationContext, llmResponse, modelResponseEvent) {
1358
- const callbackContext = new CallbackContext({
713
+ const callbackContext = new Context({
1359
714
  invocationContext,
1360
715
  eventActions: modelResponseEvent.actions
1361
716
  });
@@ -1396,7 +751,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1396
751
  }
1397
752
  }
1398
753
  } catch (modelError) {
1399
- const callbackContext = new CallbackContext({
754
+ const callbackContext = new Context({
1400
755
  invocationContext,
1401
756
  eventActions: modelResponseEvent.actions
1402
757
  });
@@ -1449,7 +804,5 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
1449
804
  }
1450
805
  export {
1451
806
  LlmAgent,
1452
- REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
1453
- isLlmAgent,
1454
- responseProcessor
807
+ isLlmAgent
1455
808
  };