@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
@@ -0,0 +1,100 @@
1
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
2
+ var __await = function(promise, isYieldStar) {
3
+ this[0] = promise;
4
+ this[1] = isYieldStar;
5
+ };
6
+ var __asyncGenerator = (__this, __arguments, generator) => {
7
+ var resume = (k, v, yes, no) => {
8
+ try {
9
+ var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
10
+ Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no));
11
+ } catch (e) {
12
+ no(e);
13
+ }
14
+ }, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
15
+ return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
16
+ };
17
+ /**
18
+ * @license
19
+ * Copyright 2025 Google LLC
20
+ * SPDX-License-Identifier: Apache-2.0
21
+ */
22
+ import { z } from "zod";
23
+ import { appendInstructions } from "../../models/llm_request.js";
24
+ import { FunctionTool } from "../../tools/function_tool.js";
25
+ import { Context } from "../context.js";
26
+ import { isLlmAgent } from "../llm_agent.js";
27
+ import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
28
+ class AgentTransferLlmRequestProcessor extends BaseLlmRequestProcessor {
29
+ constructor() {
30
+ super(...arguments);
31
+ this.toolName = "transfer_to_agent";
32
+ this.tool = new FunctionTool({
33
+ name: this.toolName,
34
+ 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.",
35
+ parameters: z.object({
36
+ agentName: z.string().describe("the agent name to transfer to.")
37
+ }),
38
+ execute: function(args, toolContext) {
39
+ if (!toolContext) {
40
+ throw new Error("toolContext is required.");
41
+ }
42
+ toolContext.actions.transferToAgent = args.agentName;
43
+ return "Transfer queued";
44
+ }
45
+ });
46
+ }
47
+ // eslint-disable-next-line require-yield
48
+ runAsync(invocationContext, llmRequest) {
49
+ return __asyncGenerator(this, null, function* () {
50
+ if (!isLlmAgent(invocationContext.agent)) {
51
+ return;
52
+ }
53
+ const transferTargets = this.getTransferTargets(invocationContext.agent);
54
+ if (!transferTargets.length) {
55
+ return;
56
+ }
57
+ appendInstructions(llmRequest, [
58
+ this.buildTargetAgentsInstructions(
59
+ invocationContext.agent,
60
+ transferTargets
61
+ )
62
+ ]);
63
+ const toolContext = new Context({ invocationContext });
64
+ yield new __await(this.tool.processLlmRequest({ toolContext, llmRequest }));
65
+ });
66
+ }
67
+ buildTargetAgentsInfo(targetAgent) {
68
+ return "\nAgent name: ".concat(targetAgent.name, "\nAgent description: ").concat(targetAgent.description, "\n");
69
+ }
70
+ buildTargetAgentsInstructions(agent, targetAgents) {
71
+ let instructions = "\nYou have a list of other agents to transfer to:\n\n".concat(targetAgents.map((t) => this.buildTargetAgentsInfo(t)).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");
72
+ if (agent.parentAgent && !agent.disallowTransferToParent) {
73
+ 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");
74
+ }
75
+ return instructions;
76
+ }
77
+ getTransferTargets(agent) {
78
+ const targets = [];
79
+ targets.push(...agent.subAgents);
80
+ if (!agent.parentAgent || !isLlmAgent(agent.parentAgent)) {
81
+ return targets;
82
+ }
83
+ if (!agent.disallowTransferToParent) {
84
+ targets.push(agent.parentAgent);
85
+ }
86
+ if (!agent.disallowTransferToPeers) {
87
+ targets.push(
88
+ ...agent.parentAgent.subAgents.filter(
89
+ (peerAgent) => peerAgent.name !== agent.name
90
+ )
91
+ );
92
+ }
93
+ return targets;
94
+ }
95
+ }
96
+ const AGENT_TRANSFER_LLM_REQUEST_PROCESSOR = new AgentTransferLlmRequestProcessor();
97
+ export {
98
+ AGENT_TRANSFER_LLM_REQUEST_PROCESSOR,
99
+ AgentTransferLlmRequestProcessor
100
+ };
@@ -0,0 +1,71 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __spreadValues = (a, b) => {
8
+ for (var prop in b || (b = {}))
9
+ if (__hasOwnProp.call(b, prop))
10
+ __defNormalProp(a, prop, b[prop]);
11
+ if (__getOwnPropSymbols)
12
+ for (var prop of __getOwnPropSymbols(b)) {
13
+ if (__propIsEnum.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ }
16
+ return a;
17
+ };
18
+ var __await = function(promise, isYieldStar) {
19
+ this[0] = promise;
20
+ this[1] = isYieldStar;
21
+ };
22
+ var __asyncGenerator = (__this, __arguments, generator) => {
23
+ var resume = (k, v, yes, no) => {
24
+ try {
25
+ var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
26
+ Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no));
27
+ } catch (e) {
28
+ no(e);
29
+ }
30
+ }, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
31
+ return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
32
+ };
33
+ /**
34
+ * @license
35
+ * Copyright 2025 Google LLC
36
+ * SPDX-License-Identifier: Apache-2.0
37
+ */
38
+ import { setOutputSchema } from "../../models/llm_request.js";
39
+ import { isLlmAgent } from "../llm_agent.js";
40
+ import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
41
+ class BasicLlmRequestProcessor extends BaseLlmRequestProcessor {
42
+ // eslint-disable-next-line require-yield
43
+ runAsync(invocationContext, llmRequest) {
44
+ return __asyncGenerator(this, null, function* () {
45
+ var _a;
46
+ const agent = invocationContext.agent;
47
+ if (!isLlmAgent(agent)) {
48
+ return;
49
+ }
50
+ llmRequest.model = agent.canonicalModel.model;
51
+ llmRequest.config = __spreadValues({}, (_a = agent.generateContentConfig) != null ? _a : {});
52
+ if (agent.outputSchema) {
53
+ setOutputSchema(llmRequest, agent.outputSchema);
54
+ }
55
+ if (invocationContext.runConfig) {
56
+ llmRequest.liveConnectConfig.responseModalities = invocationContext.runConfig.responseModalities;
57
+ llmRequest.liveConnectConfig.speechConfig = invocationContext.runConfig.speechConfig;
58
+ llmRequest.liveConnectConfig.outputAudioTranscription = invocationContext.runConfig.outputAudioTranscription;
59
+ llmRequest.liveConnectConfig.inputAudioTranscription = invocationContext.runConfig.inputAudioTranscription;
60
+ llmRequest.liveConnectConfig.realtimeInputConfig = invocationContext.runConfig.realtimeInputConfig;
61
+ llmRequest.liveConnectConfig.enableAffectiveDialog = invocationContext.runConfig.enableAffectiveDialog;
62
+ llmRequest.liveConnectConfig.proactivity = invocationContext.runConfig.proactivity;
63
+ }
64
+ });
65
+ }
66
+ }
67
+ const BASIC_LLM_REQUEST_PROCESSOR = new BasicLlmRequestProcessor();
68
+ export {
69
+ BASIC_LLM_REQUEST_PROCESSOR,
70
+ BasicLlmRequestProcessor
71
+ };
@@ -0,0 +1,365 @@
1
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
2
+ var __await = function(promise, isYieldStar) {
3
+ this[0] = promise;
4
+ this[1] = isYieldStar;
5
+ };
6
+ var __asyncGenerator = (__this, __arguments, generator) => {
7
+ var resume = (k, v, yes, no) => {
8
+ try {
9
+ var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
10
+ Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no));
11
+ } catch (e) {
12
+ no(e);
13
+ }
14
+ }, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
15
+ return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
16
+ };
17
+ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
18
+ /**
19
+ * @license
20
+ * Copyright 2025 Google LLC
21
+ * SPDX-License-Identifier: Apache-2.0
22
+ */
23
+ import { cloneDeep } from "lodash-es";
24
+ import { isBaseCodeExecutor } from "../../code_executors/base_code_executor.js";
25
+ import { isBuiltInCodeExecutor } from "../../code_executors/built_in_code_executor.js";
26
+ import {
27
+ buildCodeExecutionResultPart,
28
+ buildExecutableCodePart,
29
+ convertCodeExecutionParts,
30
+ extractCodeAndTruncateContent
31
+ } from "../../code_executors/code_execution_utils.js";
32
+ import { CodeExecutorContext } from "../../code_executors/code_executor_context.js";
33
+ import { createEvent } from "../../events/event.js";
34
+ import { createEventActions } from "../../events/event_actions.js";
35
+ import { State } from "../../sessions/state.js";
36
+ import { base64Decode } from "../../utils/env_aware_utils.js";
37
+ import { isLlmAgent } from "../llm_agent.js";
38
+ import {
39
+ BaseLlmRequestProcessor
40
+ } from "./base_llm_processor.js";
41
+ class CodeExecutionRequestProcessor extends BaseLlmRequestProcessor {
42
+ runAsync(invocationContext, llmRequest) {
43
+ return __asyncGenerator(this, null, function* () {
44
+ if (!isLlmAgent(invocationContext.agent)) {
45
+ return;
46
+ }
47
+ if (!invocationContext.agent.codeExecutor) {
48
+ return;
49
+ }
50
+ try {
51
+ for (var iter = __forAwait(runPreProcessor(invocationContext, llmRequest)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
52
+ const event = temp.value;
53
+ yield event;
54
+ }
55
+ } catch (temp) {
56
+ error = [temp];
57
+ } finally {
58
+ try {
59
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
60
+ } finally {
61
+ if (error)
62
+ throw error[0];
63
+ }
64
+ }
65
+ if (!isBaseCodeExecutor(invocationContext.agent.codeExecutor)) {
66
+ return;
67
+ }
68
+ for (const content of llmRequest.contents) {
69
+ const delimeters = invocationContext.agent.codeExecutor.codeBlockDelimiters.length ? invocationContext.agent.codeExecutor.codeBlockDelimiters[0] : ["", ""];
70
+ convertCodeExecutionParts(
71
+ content,
72
+ delimeters,
73
+ invocationContext.agent.codeExecutor.executionResultDelimiters
74
+ );
75
+ }
76
+ });
77
+ }
78
+ }
79
+ const DATA_FILE_UTIL_MAP = {
80
+ "text/csv": {
81
+ extension: ".csv",
82
+ loaderCodeTemplate: "pd.read_csv('{filename}')"
83
+ }
84
+ };
85
+ 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";
86
+ class CodeExecutionResponseProcessor {
87
+ /**
88
+ * Processes the LLM response asynchronously.
89
+ *
90
+ * @param invocationContext The invocation context
91
+ * @param llmResponse The LLM response to process
92
+ * @returns An async generator yielding events
93
+ */
94
+ runAsync(invocationContext, llmResponse) {
95
+ return __asyncGenerator(this, null, function* () {
96
+ if (llmResponse.partial) {
97
+ return;
98
+ }
99
+ try {
100
+ for (var iter = __forAwait(runPostProcessor(
101
+ invocationContext,
102
+ llmResponse
103
+ )), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
104
+ const event = temp.value;
105
+ yield event;
106
+ }
107
+ } catch (temp) {
108
+ error = [temp];
109
+ } finally {
110
+ try {
111
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
112
+ } finally {
113
+ if (error)
114
+ throw error[0];
115
+ }
116
+ }
117
+ });
118
+ }
119
+ }
120
+ const responseProcessor = new CodeExecutionResponseProcessor();
121
+ function runPreProcessor(invocationContext, llmRequest) {
122
+ return __asyncGenerator(this, null, function* () {
123
+ const agent = invocationContext.agent;
124
+ if (!isLlmAgent(agent)) {
125
+ return;
126
+ }
127
+ const codeExecutor = agent.codeExecutor;
128
+ if (!codeExecutor || !isBaseCodeExecutor(codeExecutor)) {
129
+ return;
130
+ }
131
+ if (isBuiltInCodeExecutor(codeExecutor)) {
132
+ codeExecutor.processLlmRequest(llmRequest);
133
+ return;
134
+ }
135
+ if (!codeExecutor.optimizeDataFile) {
136
+ return;
137
+ }
138
+ const codeExecutorContext = new CodeExecutorContext(
139
+ new State(invocationContext.session.state)
140
+ );
141
+ if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
142
+ return;
143
+ }
144
+ const allInputFiles = extractAndReplaceInlineFiles(
145
+ codeExecutorContext,
146
+ llmRequest
147
+ );
148
+ const processedFileNames = new Set(
149
+ codeExecutorContext.getProcessedFileNames()
150
+ );
151
+ const filesToProcess = allInputFiles.filter(
152
+ (f) => !processedFileNames.has(f.name)
153
+ );
154
+ for (const file of filesToProcess) {
155
+ const codeStr = getDataFilePreprocessingCode(file);
156
+ if (!codeStr) {
157
+ return;
158
+ }
159
+ const codeContent = {
160
+ role: "model",
161
+ parts: [
162
+ { text: "Processing input file: `".concat(file.name, "`") },
163
+ buildExecutableCodePart(codeStr)
164
+ ]
165
+ };
166
+ llmRequest.contents.push(cloneDeep(codeContent));
167
+ yield createEvent({
168
+ invocationId: invocationContext.invocationId,
169
+ author: agent.name,
170
+ branch: invocationContext.branch,
171
+ content: codeContent
172
+ });
173
+ const executionId = getOrSetExecutionId(
174
+ invocationContext,
175
+ codeExecutorContext
176
+ );
177
+ const codeExecutionResult = yield new __await(codeExecutor.executeCode({
178
+ invocationContext,
179
+ codeExecutionInput: {
180
+ code: codeStr,
181
+ inputFiles: [file],
182
+ executionId
183
+ }
184
+ }));
185
+ codeExecutorContext.updateCodeExecutionResult({
186
+ invocationId: invocationContext.invocationId,
187
+ code: codeStr,
188
+ resultStdout: codeExecutionResult.stdout,
189
+ resultStderr: codeExecutionResult.stderr
190
+ });
191
+ codeExecutorContext.addProcessedFileNames([file.name]);
192
+ const executionResultEvent = yield new __await(postProcessCodeExecutionResult(
193
+ invocationContext,
194
+ codeExecutorContext,
195
+ codeExecutionResult
196
+ ));
197
+ yield executionResultEvent;
198
+ llmRequest.contents.push(cloneDeep(executionResultEvent.content));
199
+ }
200
+ });
201
+ }
202
+ function runPostProcessor(invocationContext, llmResponse) {
203
+ return __asyncGenerator(this, null, function* () {
204
+ const agent = invocationContext.agent;
205
+ if (!isLlmAgent(agent)) {
206
+ return;
207
+ }
208
+ const codeExecutor = agent.codeExecutor;
209
+ if (!codeExecutor || !isBaseCodeExecutor(codeExecutor)) {
210
+ return;
211
+ }
212
+ if (!llmResponse || !llmResponse.content) {
213
+ return;
214
+ }
215
+ if (isBuiltInCodeExecutor(codeExecutor)) {
216
+ return;
217
+ }
218
+ const codeExecutorContext = new CodeExecutorContext(
219
+ new State(invocationContext.session.state)
220
+ );
221
+ if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
222
+ return;
223
+ }
224
+ const responseContent = llmResponse.content;
225
+ const codeStr = extractCodeAndTruncateContent(
226
+ responseContent,
227
+ codeExecutor.codeBlockDelimiters
228
+ );
229
+ if (!codeStr) {
230
+ return;
231
+ }
232
+ yield createEvent({
233
+ invocationId: invocationContext.invocationId,
234
+ author: agent.name,
235
+ branch: invocationContext.branch,
236
+ content: responseContent
237
+ });
238
+ const executionId = getOrSetExecutionId(
239
+ invocationContext,
240
+ codeExecutorContext
241
+ );
242
+ const codeExecutionResult = yield new __await(codeExecutor.executeCode({
243
+ invocationContext,
244
+ codeExecutionInput: {
245
+ code: codeStr,
246
+ inputFiles: codeExecutorContext.getInputFiles(),
247
+ executionId
248
+ }
249
+ }));
250
+ codeExecutorContext.updateCodeExecutionResult({
251
+ invocationId: invocationContext.invocationId,
252
+ code: codeStr,
253
+ resultStdout: codeExecutionResult.stdout,
254
+ resultStderr: codeExecutionResult.stderr
255
+ });
256
+ yield yield new __await(postProcessCodeExecutionResult(
257
+ invocationContext,
258
+ codeExecutorContext,
259
+ codeExecutionResult
260
+ ));
261
+ llmResponse.content = void 0;
262
+ });
263
+ }
264
+ function extractAndReplaceInlineFiles(codeExecutorContext, llmRequest) {
265
+ var _a;
266
+ const allInputFiles = codeExecutorContext.getInputFiles();
267
+ const savedFileNames = new Set(allInputFiles.map((f) => f.name));
268
+ for (let i = 0; i < llmRequest.contents.length; i++) {
269
+ const content = llmRequest.contents[i];
270
+ if (content.role !== "user" || !content.parts) {
271
+ continue;
272
+ }
273
+ for (let j = 0; j < content.parts.length; j++) {
274
+ const part = content.parts[j];
275
+ const mimeType = (_a = part.inlineData) == null ? void 0 : _a.mimeType;
276
+ if (!mimeType || !part.inlineData || !DATA_FILE_UTIL_MAP[mimeType]) {
277
+ continue;
278
+ }
279
+ const fileName = "data_".concat(i + 1, "_").concat(j + 1).concat(DATA_FILE_UTIL_MAP[mimeType].extension);
280
+ part.text = "\nAvailable file: `".concat(fileName, "`\n");
281
+ const file = {
282
+ name: fileName,
283
+ content: base64Decode(part.inlineData.data),
284
+ mimeType
285
+ };
286
+ if (!savedFileNames.has(fileName)) {
287
+ codeExecutorContext.addInputFiles([file]);
288
+ allInputFiles.push(file);
289
+ }
290
+ }
291
+ }
292
+ return allInputFiles;
293
+ }
294
+ function getOrSetExecutionId(invocationContext, codeExecutorContext) {
295
+ var _a;
296
+ const agent = invocationContext.agent;
297
+ if (!isLlmAgent(agent) || !((_a = agent.codeExecutor) == null ? void 0 : _a.stateful)) {
298
+ return void 0;
299
+ }
300
+ let executionId = codeExecutorContext.getExecutionId();
301
+ if (!executionId) {
302
+ executionId = invocationContext.session.id;
303
+ codeExecutorContext.setExecutionId(executionId);
304
+ }
305
+ return executionId;
306
+ }
307
+ async function postProcessCodeExecutionResult(invocationContext, codeExecutorContext, codeExecutionResult) {
308
+ if (!invocationContext.artifactService) {
309
+ throw new Error("Artifact service is not initialized.");
310
+ }
311
+ const resultContent = {
312
+ role: "model",
313
+ parts: [buildCodeExecutionResultPart(codeExecutionResult)]
314
+ };
315
+ const eventActions = createEventActions({
316
+ stateDelta: codeExecutorContext.getStateDelta()
317
+ });
318
+ if (codeExecutionResult.stderr) {
319
+ codeExecutorContext.incrementErrorCount(invocationContext.invocationId);
320
+ } else {
321
+ codeExecutorContext.resetErrorCount(invocationContext.invocationId);
322
+ }
323
+ for (const outputFile of codeExecutionResult.outputFiles) {
324
+ const version = await invocationContext.artifactService.saveArtifact({
325
+ appName: invocationContext.appName || "",
326
+ userId: invocationContext.userId || "",
327
+ sessionId: invocationContext.session.id,
328
+ filename: outputFile.name,
329
+ artifact: {
330
+ inlineData: { data: outputFile.content, mimeType: outputFile.mimeType }
331
+ }
332
+ });
333
+ eventActions.artifactDelta[outputFile.name] = version;
334
+ }
335
+ return createEvent({
336
+ invocationId: invocationContext.invocationId,
337
+ author: invocationContext.agent.name,
338
+ branch: invocationContext.branch,
339
+ content: resultContent,
340
+ actions: eventActions
341
+ });
342
+ }
343
+ function getDataFilePreprocessingCode(file) {
344
+ function getNormalizedFileName(fileName) {
345
+ const [varName2] = fileName.split(".");
346
+ let normalizedName = varName2.replace(/[^a-zA-Z0-9_]/g, "_");
347
+ if (/^\d/.test(normalizedName)) {
348
+ normalizedName = "_" + normalizedName;
349
+ }
350
+ return normalizedName;
351
+ }
352
+ if (!DATA_FILE_UTIL_MAP[file.mimeType]) {
353
+ return void 0;
354
+ }
355
+ const varName = getNormalizedFileName(file.name);
356
+ const loaderCode = DATA_FILE_UTIL_MAP[file.mimeType].loaderCodeTemplate.replace("{filename}", file.name);
357
+ 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");
358
+ }
359
+ const CODE_EXECUTION_REQUEST_PROCESSOR = new CodeExecutionRequestProcessor();
360
+ export {
361
+ CODE_EXECUTION_REQUEST_PROCESSOR,
362
+ CodeExecutionRequestProcessor,
363
+ CodeExecutionResponseProcessor,
364
+ responseProcessor
365
+ };
@@ -0,0 +1,56 @@
1
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
2
+ var __await = function(promise, isYieldStar) {
3
+ this[0] = promise;
4
+ this[1] = isYieldStar;
5
+ };
6
+ var __asyncGenerator = (__this, __arguments, generator) => {
7
+ var resume = (k, v, yes, no) => {
8
+ try {
9
+ var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
10
+ Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no));
11
+ } catch (e) {
12
+ no(e);
13
+ }
14
+ }, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
15
+ return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
16
+ };
17
+ /**
18
+ * @license
19
+ * Copyright 2025 Google LLC
20
+ * SPDX-License-Identifier: Apache-2.0
21
+ */
22
+ import {
23
+ getContents,
24
+ getCurrentTurnContents
25
+ } from "../content_processor_utils.js";
26
+ import { isLlmAgent } from "../llm_agent.js";
27
+ class ContentRequestProcessor {
28
+ // eslint-disable-next-line require-yield
29
+ runAsync(invocationContext, llmRequest) {
30
+ return __asyncGenerator(this, null, function* () {
31
+ const agent = invocationContext.agent;
32
+ if (!agent || !isLlmAgent(agent)) {
33
+ return;
34
+ }
35
+ if (agent.includeContents === "default") {
36
+ llmRequest.contents = getContents(
37
+ invocationContext.session.events,
38
+ agent.name,
39
+ invocationContext.branch
40
+ );
41
+ } else {
42
+ llmRequest.contents = getCurrentTurnContents(
43
+ invocationContext.session.events,
44
+ agent.name,
45
+ invocationContext.branch
46
+ );
47
+ }
48
+ return;
49
+ });
50
+ }
51
+ }
52
+ const CONTENT_REQUEST_PROCESSOR = new ContentRequestProcessor();
53
+ export {
54
+ CONTENT_REQUEST_PROCESSOR,
55
+ ContentRequestProcessor
56
+ };
@@ -0,0 +1,41 @@
1
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
2
+ var __await = function(promise, isYieldStar) {
3
+ this[0] = promise;
4
+ this[1] = isYieldStar;
5
+ };
6
+ var __asyncGenerator = (__this, __arguments, generator) => {
7
+ var resume = (k, v, yes, no) => {
8
+ try {
9
+ var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
10
+ Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no));
11
+ } catch (e) {
12
+ no(e);
13
+ }
14
+ }, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
15
+ return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
16
+ };
17
+ /**
18
+ * @license
19
+ * Copyright 2025 Google LLC
20
+ * SPDX-License-Identifier: Apache-2.0
21
+ */
22
+ import { appendInstructions } from "../../models/llm_request.js";
23
+ import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
24
+ class IdentityLlmRequestProcessor extends BaseLlmRequestProcessor {
25
+ // eslint-disable-next-line require-yield
26
+ runAsync(invocationContext, llmRequest) {
27
+ return __asyncGenerator(this, null, function* () {
28
+ const agent = invocationContext.agent;
29
+ const si = ['You are an agent. Your internal name is "'.concat(agent.name, '".')];
30
+ if (agent.description) {
31
+ si.push('The description about you is "'.concat(agent.description, '"'));
32
+ }
33
+ appendInstructions(llmRequest, si);
34
+ });
35
+ }
36
+ }
37
+ const IDENTITY_LLM_REQUEST_PROCESSOR = new IdentityLlmRequestProcessor();
38
+ export {
39
+ IDENTITY_LLM_REQUEST_PROCESSOR,
40
+ IdentityLlmRequestProcessor
41
+ };