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