@google/adk 0.3.0 → 0.4.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.
- package/dist/cjs/a2a/part_converter_utils.js +210 -0
- package/dist/cjs/agents/active_streaming_tool.js +1 -1
- package/dist/cjs/agents/base_agent.js +3 -3
- package/dist/cjs/agents/base_llm_processor.js +1 -1
- package/dist/cjs/agents/callback_context.js +1 -1
- package/dist/cjs/agents/content_processor_utils.js +1 -1
- package/dist/cjs/agents/functions.js +2 -1
- package/dist/cjs/agents/instructions.js +1 -1
- package/dist/cjs/agents/invocation_context.js +1 -1
- package/dist/cjs/agents/live_request_queue.js +1 -1
- package/dist/cjs/agents/llm_agent.js +58 -40
- package/dist/cjs/agents/loop_agent.js +1 -1
- package/dist/cjs/agents/parallel_agent.js +1 -1
- package/dist/cjs/agents/readonly_context.js +13 -1
- package/dist/cjs/agents/run_config.js +2 -1
- package/dist/cjs/agents/sequential_agent.js +1 -1
- package/dist/cjs/agents/transcription_entry.js +1 -1
- package/dist/cjs/artifacts/base_artifact_service.js +1 -1
- package/dist/cjs/artifacts/file_artifact_service.js +491 -0
- package/dist/cjs/artifacts/gcs_artifact_service.js +127 -48
- package/dist/cjs/artifacts/in_memory_artifact_service.js +54 -6
- package/dist/cjs/artifacts/registry.js +55 -0
- package/dist/cjs/auth/auth_credential.js +1 -1
- package/dist/cjs/auth/auth_handler.js +1 -1
- package/dist/cjs/auth/auth_schemes.js +1 -1
- package/dist/cjs/auth/auth_tool.js +1 -1
- package/dist/cjs/auth/credential_service/base_credential_service.js +1 -1
- package/dist/cjs/auth/credential_service/in_memory_credential_service.js +1 -1
- package/dist/cjs/auth/exchanger/base_credential_exchanger.js +1 -1
- package/dist/cjs/auth/exchanger/credential_exchanger_registry.js +1 -1
- package/dist/cjs/code_executors/base_code_executor.js +1 -1
- package/dist/cjs/code_executors/built_in_code_executor.js +1 -1
- package/dist/cjs/code_executors/code_execution_utils.js +1 -1
- package/dist/cjs/code_executors/code_executor_context.js +1 -1
- package/dist/cjs/common.js +14 -1
- package/dist/cjs/events/event.js +33 -4
- package/dist/cjs/events/event_actions.js +2 -2
- package/dist/cjs/events/structured_events.js +105 -0
- package/dist/cjs/examples/base_example_provider.js +1 -1
- package/dist/cjs/examples/example.js +1 -1
- package/dist/cjs/examples/example_util.js +1 -1
- package/dist/cjs/index.js +54 -83
- package/dist/cjs/index_web.js +1 -1
- package/dist/cjs/memory/base_memory_service.js +1 -1
- package/dist/cjs/memory/in_memory_memory_service.js +1 -1
- package/dist/cjs/memory/memory_entry.js +1 -1
- package/dist/cjs/models/apigee_llm.js +182 -0
- package/dist/cjs/models/base_llm.js +1 -1
- package/dist/cjs/models/base_llm_connection.js +1 -1
- package/dist/cjs/models/gemini_llm_connection.js +1 -1
- package/dist/cjs/models/google_llm.js +70 -51
- package/dist/cjs/models/llm_request.js +1 -1
- package/dist/cjs/models/llm_response.js +1 -1
- package/dist/cjs/models/registry.js +3 -1
- package/dist/cjs/plugins/base_plugin.js +1 -1
- package/dist/cjs/plugins/logging_plugin.js +1 -1
- package/dist/cjs/plugins/plugin_manager.js +1 -1
- package/dist/cjs/plugins/security_plugin.js +1 -1
- package/dist/cjs/runner/in_memory_runner.js +1 -1
- package/dist/cjs/runner/runner.js +32 -1
- package/dist/cjs/sessions/base_session_service.js +53 -3
- package/dist/cjs/sessions/database_session_service.js +364 -0
- package/dist/cjs/sessions/db/operations.js +114 -0
- package/dist/cjs/sessions/db/schema.js +204 -0
- package/dist/cjs/sessions/in_memory_session_service.js +24 -22
- package/dist/cjs/sessions/registry.js +49 -0
- package/dist/cjs/sessions/session.js +1 -1
- package/dist/cjs/sessions/state.js +1 -1
- package/dist/cjs/telemetry/google_cloud.js +1 -1
- package/dist/cjs/telemetry/setup.js +1 -1
- package/dist/cjs/telemetry/tracing.js +1 -1
- package/dist/cjs/tools/agent_tool.js +1 -1
- package/dist/cjs/tools/base_tool.js +1 -1
- package/dist/cjs/tools/base_toolset.js +1 -1
- package/dist/cjs/tools/forwarding_artifact_service.js +17 -1
- package/dist/cjs/tools/function_tool.js +1 -1
- package/dist/cjs/tools/google_search_tool.js +1 -1
- package/dist/cjs/tools/long_running_tool.js +1 -1
- package/dist/cjs/tools/mcp/mcp_session_manager.js +1 -1
- package/dist/cjs/tools/mcp/mcp_tool.js +1 -1
- package/dist/cjs/tools/mcp/mcp_toolset.js +1 -1
- package/dist/cjs/tools/tool_confirmation.js +1 -1
- package/dist/cjs/tools/tool_context.js +1 -1
- package/dist/cjs/utils/client_labels.js +1 -1
- package/dist/cjs/utils/env_aware_utils.js +10 -1
- package/dist/cjs/utils/gemini_schema_util.js +1 -1
- package/dist/cjs/utils/logger.js +1 -1
- package/dist/cjs/utils/model_name.js +1 -1
- package/dist/cjs/utils/object_notation_utils.js +78 -0
- package/dist/cjs/utils/simple_zod_to_json.js +1 -1
- package/dist/cjs/utils/variant_utils.js +3 -9
- package/dist/cjs/version.js +2 -2
- package/dist/esm/a2a/part_converter_utils.js +171 -0
- package/dist/esm/agents/base_agent.js +2 -2
- package/dist/esm/agents/functions.js +1 -0
- package/dist/esm/agents/llm_agent.js +58 -40
- package/dist/esm/agents/readonly_context.js +12 -0
- package/dist/esm/agents/run_config.js +1 -0
- package/dist/esm/artifacts/file_artifact_service.js +451 -0
- package/dist/esm/artifacts/gcs_artifact_service.js +126 -47
- package/dist/esm/artifacts/in_memory_artifact_service.js +51 -4
- package/dist/esm/artifacts/registry.js +28 -0
- package/dist/esm/common.js +9 -1
- package/dist/esm/events/event.js +29 -2
- package/dist/esm/events/event_actions.js +1 -1
- package/dist/esm/events/structured_events.js +74 -0
- package/dist/esm/index.js +18 -88
- package/dist/esm/models/apigee_llm.js +152 -0
- package/dist/esm/models/google_llm.js +67 -49
- package/dist/esm/models/registry.js +2 -0
- package/dist/esm/runner/runner.js +31 -0
- package/dist/esm/sessions/base_session_service.js +49 -1
- package/dist/esm/sessions/database_session_service.js +350 -0
- package/dist/esm/sessions/db/operations.js +87 -0
- package/dist/esm/sessions/db/schema.js +172 -0
- package/dist/esm/sessions/in_memory_session_service.js +23 -21
- package/dist/esm/sessions/registry.js +25 -0
- package/dist/esm/tools/forwarding_artifact_service.js +16 -0
- package/dist/esm/utils/env_aware_utils.js +8 -0
- package/dist/esm/utils/object_notation_utils.js +47 -0
- package/dist/esm/utils/variant_utils.js +1 -7
- package/dist/esm/version.js +1 -1
- package/dist/types/a2a/part_converter_utils.d.ts +47 -0
- package/dist/types/agents/llm_agent.d.ts +11 -11
- package/dist/types/agents/readonly_context.d.ts +8 -0
- package/dist/types/agents/run_config.d.ts +6 -0
- package/dist/types/artifacts/base_artifact_service.d.ts +31 -0
- package/dist/types/artifacts/file_artifact_service.d.ts +43 -0
- package/dist/types/artifacts/gcs_artifact_service.d.ts +3 -1
- package/dist/types/artifacts/in_memory_artifact_service.d.ts +5 -2
- package/dist/types/artifacts/registry.d.ts +7 -0
- package/dist/types/common.d.ts +11 -2
- package/dist/types/events/event.d.ts +15 -1
- package/dist/types/events/event_actions.d.ts +1 -1
- package/dist/types/events/structured_events.d.ts +106 -0
- package/dist/types/index.d.ts +5 -1
- package/dist/types/models/apigee_llm.d.ts +59 -0
- package/dist/types/models/google_llm.d.ts +5 -2
- package/dist/types/runner/runner.d.ts +15 -0
- package/dist/types/sessions/base_session_service.d.ts +20 -0
- package/dist/types/sessions/database_session_service.d.ts +31 -0
- package/dist/types/sessions/db/operations.d.ts +29 -0
- package/dist/types/sessions/db/schema.d.ts +45 -0
- package/dist/types/sessions/in_memory_session_service.d.ts +4 -1
- package/dist/types/sessions/registry.d.ts +7 -0
- package/dist/types/tools/forwarding_artifact_service.d.ts +3 -1
- package/dist/types/utils/env_aware_utils.d.ts +7 -0
- package/dist/types/utils/object_notation_utils.d.ts +21 -0
- package/dist/types/version.d.ts +1 -1
- package/dist/web/a2a/part_converter_utils.js +171 -0
- package/dist/web/agents/base_agent.js +2 -2
- package/dist/web/agents/functions.js +1 -0
- package/dist/web/agents/llm_agent.js +79 -59
- package/dist/web/agents/readonly_context.js +12 -0
- package/dist/web/agents/run_config.js +2 -1
- package/dist/web/artifacts/file_artifact_service.js +506 -0
- package/dist/web/artifacts/gcs_artifact_service.js +123 -46
- package/dist/web/artifacts/in_memory_artifact_service.js +51 -4
- package/dist/web/artifacts/registry.js +28 -0
- package/dist/web/common.js +9 -1
- package/dist/web/events/event.js +29 -2
- package/dist/web/events/event_actions.js +1 -1
- package/dist/web/events/structured_events.js +74 -0
- package/dist/web/index.js +18 -8
- package/dist/web/models/apigee_llm.js +219 -0
- package/dist/web/models/google_llm.js +67 -46
- package/dist/web/models/registry.js +2 -0
- package/dist/web/runner/runner.js +33 -0
- package/dist/web/sessions/base_session_service.js +49 -1
- package/dist/web/sessions/database_session_service.js +368 -0
- package/dist/web/sessions/db/operations.js +87 -0
- package/dist/web/sessions/db/schema.js +172 -0
- package/dist/web/sessions/in_memory_session_service.js +23 -21
- package/dist/web/sessions/registry.js +25 -0
- package/dist/web/tools/forwarding_artifact_service.js +16 -0
- package/dist/web/utils/env_aware_utils.js +8 -0
- package/dist/web/utils/object_notation_utils.js +47 -0
- package/dist/web/utils/variant_utils.js +1 -7
- package/dist/web/version.js +1 -1
- package/package.json +13 -4
- package/dist/cjs/index.js.map +0 -7
- package/dist/esm/index.js.map +0 -7
- package/dist/web/index.js.map +0 -7
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
* Copyright 2025 Google LLC
|
|
4
4
|
* SPDX-License-Identifier: Apache-2.0
|
|
5
5
|
*/
|
|
6
|
+
function isInMemoryConnectionString(uri) {
|
|
7
|
+
return uri === "memory://";
|
|
8
|
+
}
|
|
6
9
|
class InMemoryArtifactService {
|
|
7
10
|
constructor() {
|
|
8
11
|
this.artifacts = {};
|
|
@@ -12,14 +15,24 @@ class InMemoryArtifactService {
|
|
|
12
15
|
userId,
|
|
13
16
|
sessionId,
|
|
14
17
|
filename,
|
|
15
|
-
artifact
|
|
18
|
+
artifact,
|
|
19
|
+
customMetadata
|
|
16
20
|
}) {
|
|
21
|
+
if (!artifact.inlineData && !artifact.text) {
|
|
22
|
+
return Promise.reject(
|
|
23
|
+
new Error("Artifact must have either inlineData or text content.")
|
|
24
|
+
);
|
|
25
|
+
}
|
|
17
26
|
const path = artifactPath(appName, userId, sessionId, filename);
|
|
18
27
|
if (!this.artifacts[path]) {
|
|
19
28
|
this.artifacts[path] = [];
|
|
20
29
|
}
|
|
21
30
|
const version = this.artifacts[path].length;
|
|
22
|
-
|
|
31
|
+
const metadata = {
|
|
32
|
+
version,
|
|
33
|
+
customMetadata
|
|
34
|
+
};
|
|
35
|
+
this.artifacts[path].push({ part: artifact, metadata });
|
|
23
36
|
return Promise.resolve(version);
|
|
24
37
|
}
|
|
25
38
|
loadArtifact({
|
|
@@ -37,7 +50,7 @@ class InMemoryArtifactService {
|
|
|
37
50
|
if (version === void 0) {
|
|
38
51
|
version = versions.length - 1;
|
|
39
52
|
}
|
|
40
|
-
return Promise.resolve(versions[version]);
|
|
53
|
+
return Promise.resolve(versions[version].part);
|
|
41
54
|
}
|
|
42
55
|
listArtifactKeys({
|
|
43
56
|
appName,
|
|
@@ -88,6 +101,39 @@ class InMemoryArtifactService {
|
|
|
88
101
|
}
|
|
89
102
|
return Promise.resolve(versions);
|
|
90
103
|
}
|
|
104
|
+
listArtifactVersions({
|
|
105
|
+
appName,
|
|
106
|
+
userId,
|
|
107
|
+
sessionId,
|
|
108
|
+
filename
|
|
109
|
+
}) {
|
|
110
|
+
const path = artifactPath(appName, userId, sessionId, filename);
|
|
111
|
+
const artifacts = this.artifacts[path];
|
|
112
|
+
if (!artifacts) {
|
|
113
|
+
return Promise.resolve([]);
|
|
114
|
+
}
|
|
115
|
+
return Promise.resolve(artifacts.map((a) => a.metadata));
|
|
116
|
+
}
|
|
117
|
+
getArtifactVersion({
|
|
118
|
+
appName,
|
|
119
|
+
userId,
|
|
120
|
+
sessionId,
|
|
121
|
+
filename,
|
|
122
|
+
version
|
|
123
|
+
}) {
|
|
124
|
+
const path = artifactPath(appName, userId, sessionId, filename);
|
|
125
|
+
const versions = this.artifacts[path];
|
|
126
|
+
if (!versions) {
|
|
127
|
+
return Promise.resolve(void 0);
|
|
128
|
+
}
|
|
129
|
+
if (version === void 0) {
|
|
130
|
+
version = versions.length - 1;
|
|
131
|
+
}
|
|
132
|
+
if (versions[version]) {
|
|
133
|
+
return Promise.resolve(versions[version].metadata);
|
|
134
|
+
}
|
|
135
|
+
return Promise.resolve(void 0);
|
|
136
|
+
}
|
|
91
137
|
}
|
|
92
138
|
function artifactPath(appName, userId, sessionId, filename) {
|
|
93
139
|
if (fileHasUserNamespace(filename)) {
|
|
@@ -99,5 +145,6 @@ function fileHasUserNamespace(filename) {
|
|
|
99
145
|
return filename.startsWith("user:");
|
|
100
146
|
}
|
|
101
147
|
export {
|
|
102
|
-
InMemoryArtifactService
|
|
148
|
+
InMemoryArtifactService,
|
|
149
|
+
isInMemoryConnectionString
|
|
103
150
|
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Google LLC
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*/
|
|
6
|
+
import { FileArtifactService } from "./file_artifact_service.js";
|
|
7
|
+
import { GcsArtifactService } from "./gcs_artifact_service.js";
|
|
8
|
+
import {
|
|
9
|
+
InMemoryArtifactService,
|
|
10
|
+
isInMemoryConnectionString
|
|
11
|
+
} from "./in_memory_artifact_service.js";
|
|
12
|
+
function getArtifactServiceFromUri(uri) {
|
|
13
|
+
if (isInMemoryConnectionString(uri)) {
|
|
14
|
+
return new InMemoryArtifactService();
|
|
15
|
+
}
|
|
16
|
+
if (uri.startsWith("gs://")) {
|
|
17
|
+
const bucket = uri.split("://")[1];
|
|
18
|
+
return new GcsArtifactService(bucket);
|
|
19
|
+
}
|
|
20
|
+
if (uri.startsWith("file://")) {
|
|
21
|
+
const rootDir = uri.split("://")[1];
|
|
22
|
+
return new FileArtifactService(rootDir);
|
|
23
|
+
}
|
|
24
|
+
throw new Error(`Unsupported artifact service URI: ${uri}`);
|
|
25
|
+
}
|
|
26
|
+
export {
|
|
27
|
+
getArtifactServiceFromUri
|
|
28
|
+
};
|
package/dist/esm/common.js
CHANGED
|
@@ -32,13 +32,15 @@ import {
|
|
|
32
32
|
stringifyContent
|
|
33
33
|
} from "./events/event.js";
|
|
34
34
|
import { createEventActions } from "./events/event_actions.js";
|
|
35
|
+
import { EventType, toStructuredEvents } from "./events/structured_events.js";
|
|
35
36
|
import {
|
|
36
37
|
BaseExampleProvider,
|
|
37
38
|
isBaseExampleProvider
|
|
38
39
|
} from "./examples/base_example_provider.js";
|
|
39
40
|
import { InMemoryMemoryService } from "./memory/in_memory_memory_service.js";
|
|
41
|
+
import { ApigeeLlm } from "./models/apigee_llm.js";
|
|
40
42
|
import { BaseLlm, isBaseLlm } from "./models/base_llm.js";
|
|
41
|
-
import { Gemini } from "./models/google_llm.js";
|
|
43
|
+
import { Gemini, geminiInitParams } from "./models/google_llm.js";
|
|
42
44
|
import { LLMRegistry } from "./models/registry.js";
|
|
43
45
|
import { BasePlugin } from "./plugins/base_plugin.js";
|
|
44
46
|
import { LoggingPlugin } from "./plugins/logging_plugin.js";
|
|
@@ -52,6 +54,7 @@ import {
|
|
|
52
54
|
} from "./plugins/security_plugin.js";
|
|
53
55
|
import { InMemoryRunner } from "./runner/in_memory_runner.js";
|
|
54
56
|
import { Runner } from "./runner/runner.js";
|
|
57
|
+
import { BaseSessionService } from "./sessions/base_session_service.js";
|
|
55
58
|
import { InMemorySessionService } from "./sessions/in_memory_session_service.js";
|
|
56
59
|
import { createSession } from "./sessions/session.js";
|
|
57
60
|
import { State } from "./sessions/state.js";
|
|
@@ -75,6 +78,7 @@ export * from "./tools/base_tool.js";
|
|
|
75
78
|
export {
|
|
76
79
|
ActiveStreamingTool,
|
|
77
80
|
AgentTool,
|
|
81
|
+
ApigeeLlm,
|
|
78
82
|
AuthCredentialTypes,
|
|
79
83
|
BaseAgent,
|
|
80
84
|
BaseCodeExecutor,
|
|
@@ -83,10 +87,12 @@ export {
|
|
|
83
87
|
BaseLlmRequestProcessor,
|
|
84
88
|
BaseLlmResponseProcessor,
|
|
85
89
|
BasePlugin,
|
|
90
|
+
BaseSessionService,
|
|
86
91
|
BaseTool,
|
|
87
92
|
BaseToolset,
|
|
88
93
|
BuiltInCodeExecutor,
|
|
89
94
|
CallbackContext,
|
|
95
|
+
EventType,
|
|
90
96
|
FunctionTool,
|
|
91
97
|
GOOGLE_SEARCH,
|
|
92
98
|
Gemini,
|
|
@@ -121,6 +127,7 @@ export {
|
|
|
121
127
|
createEventActions,
|
|
122
128
|
createSession,
|
|
123
129
|
functionsExportedForTestingOnly,
|
|
130
|
+
geminiInitParams,
|
|
124
131
|
getAskUserConfirmationFunctionCalls,
|
|
125
132
|
getFunctionCalls,
|
|
126
133
|
getFunctionResponses,
|
|
@@ -141,6 +148,7 @@ export {
|
|
|
141
148
|
setLogLevel,
|
|
142
149
|
setLogger,
|
|
143
150
|
stringifyContent,
|
|
151
|
+
toStructuredEvents,
|
|
144
152
|
version,
|
|
145
153
|
zodObjectToSchema
|
|
146
154
|
};
|
package/dist/esm/events/event.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @license
|
|
3
|
-
* Copyright
|
|
3
|
+
* Copyright 2026 Google LLC
|
|
4
4
|
* SPDX-License-Identifier: Apache-2.0
|
|
5
5
|
*/
|
|
6
|
+
import { toCamelCase, toSnakeCase } from "../utils/object_notation_utils.js";
|
|
6
7
|
import { createEventActions } from "./event_actions.js";
|
|
7
8
|
function createEvent(params = {}) {
|
|
8
9
|
return {
|
|
@@ -70,6 +71,30 @@ function createNewEventId() {
|
|
|
70
71
|
}
|
|
71
72
|
return id;
|
|
72
73
|
}
|
|
74
|
+
const PRESERVE_KEYS_CAMEL_CASE = [
|
|
75
|
+
"actions.stateDelta",
|
|
76
|
+
"actions.artifactDelta",
|
|
77
|
+
"actions.requestedAuthConfigs",
|
|
78
|
+
"actions.requestedToolConfirmations",
|
|
79
|
+
"actions.customMetadata",
|
|
80
|
+
"content.parts.functionCall.args",
|
|
81
|
+
"content.parts.functionResponse.response"
|
|
82
|
+
];
|
|
83
|
+
const PRESERVE_KEYS_SNAKE_CASE = [
|
|
84
|
+
"actions.state_delta",
|
|
85
|
+
"actions.artifact_delta",
|
|
86
|
+
"actions.requested_auth_configs",
|
|
87
|
+
"actions.requested_tool_confirmations",
|
|
88
|
+
"actions.custom_metadata",
|
|
89
|
+
"content.parts.function_call.args",
|
|
90
|
+
"content.parts.function_response.response"
|
|
91
|
+
];
|
|
92
|
+
function transformToCamelCaseEvent(event) {
|
|
93
|
+
return toCamelCase(event, PRESERVE_KEYS_SNAKE_CASE);
|
|
94
|
+
}
|
|
95
|
+
function transformToSnakeCaseEvent(event) {
|
|
96
|
+
return toSnakeCase(event, PRESERVE_KEYS_CAMEL_CASE);
|
|
97
|
+
}
|
|
73
98
|
export {
|
|
74
99
|
createEvent,
|
|
75
100
|
createNewEventId,
|
|
@@ -77,5 +102,7 @@ export {
|
|
|
77
102
|
getFunctionResponses,
|
|
78
103
|
hasTrailingCodeExecutionResult,
|
|
79
104
|
isFinalResponse,
|
|
80
|
-
stringifyContent
|
|
105
|
+
stringifyContent,
|
|
106
|
+
transformToCamelCaseEvent,
|
|
107
|
+
transformToSnakeCaseEvent
|
|
81
108
|
};
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Google LLC
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*/
|
|
6
|
+
import { isEmpty } from "lodash-es";
|
|
7
|
+
import { isFinalResponse } from "./event.js";
|
|
8
|
+
var EventType = /* @__PURE__ */ ((EventType2) => {
|
|
9
|
+
EventType2["THOUGHT"] = "thought";
|
|
10
|
+
EventType2["CONTENT"] = "content";
|
|
11
|
+
EventType2["TOOL_CALL"] = "tool_call";
|
|
12
|
+
EventType2["TOOL_RESULT"] = "tool_result";
|
|
13
|
+
EventType2["CALL_CODE"] = "call_code";
|
|
14
|
+
EventType2["CODE_RESULT"] = "code_result";
|
|
15
|
+
EventType2["ERROR"] = "error";
|
|
16
|
+
EventType2["ACTIVITY"] = "activity";
|
|
17
|
+
EventType2["TOOL_CONFIRMATION"] = "tool_confirmation";
|
|
18
|
+
EventType2["FINISHED"] = "finished";
|
|
19
|
+
return EventType2;
|
|
20
|
+
})(EventType || {});
|
|
21
|
+
function toStructuredEvents(event) {
|
|
22
|
+
var _a, _b;
|
|
23
|
+
const structuredEvents = [];
|
|
24
|
+
if (event.errorCode) {
|
|
25
|
+
structuredEvents.push({
|
|
26
|
+
type: "error" /* ERROR */,
|
|
27
|
+
error: new Error(event.errorMessage || event.errorCode)
|
|
28
|
+
});
|
|
29
|
+
return structuredEvents;
|
|
30
|
+
}
|
|
31
|
+
for (const part of (_b = (_a = event.content) == null ? void 0 : _a.parts) != null ? _b : []) {
|
|
32
|
+
if (part.functionCall && !isEmpty(part.functionCall)) {
|
|
33
|
+
structuredEvents.push({
|
|
34
|
+
type: "tool_call" /* TOOL_CALL */,
|
|
35
|
+
call: part.functionCall
|
|
36
|
+
});
|
|
37
|
+
} else if (part.functionResponse && !isEmpty(part.functionResponse)) {
|
|
38
|
+
structuredEvents.push({
|
|
39
|
+
type: "tool_result" /* TOOL_RESULT */,
|
|
40
|
+
result: part.functionResponse
|
|
41
|
+
});
|
|
42
|
+
} else if (part.executableCode && !isEmpty(part.executableCode)) {
|
|
43
|
+
structuredEvents.push({
|
|
44
|
+
type: "call_code" /* CALL_CODE */,
|
|
45
|
+
code: part.executableCode
|
|
46
|
+
});
|
|
47
|
+
} else if (part.codeExecutionResult && !isEmpty(part.codeExecutionResult)) {
|
|
48
|
+
structuredEvents.push({
|
|
49
|
+
type: "code_result" /* CODE_RESULT */,
|
|
50
|
+
result: part.codeExecutionResult
|
|
51
|
+
});
|
|
52
|
+
} else if (part.text) {
|
|
53
|
+
if (part.thought) {
|
|
54
|
+
structuredEvents.push({ type: "thought" /* THOUGHT */, content: part.text });
|
|
55
|
+
} else {
|
|
56
|
+
structuredEvents.push({ type: "content" /* CONTENT */, content: part.text });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (event.actions.requestedToolConfirmations && !isEmpty(event.actions.requestedToolConfirmations)) {
|
|
61
|
+
structuredEvents.push({
|
|
62
|
+
type: "tool_confirmation" /* TOOL_CONFIRMATION */,
|
|
63
|
+
confirmations: event.actions.requestedToolConfirmations
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
if (isFinalResponse(event)) {
|
|
67
|
+
structuredEvents.push({ type: "finished" /* FINISHED */, output: void 0 });
|
|
68
|
+
}
|
|
69
|
+
return structuredEvents;
|
|
70
|
+
}
|
|
71
|
+
export {
|
|
72
|
+
EventType,
|
|
73
|
+
toStructuredEvents
|
|
74
|
+
};
|
package/dist/esm/index.js
CHANGED
|
@@ -1,93 +1,23 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright 2025 Google LLC
|
|
4
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import{Storage as fo}from"@google-cloud/storage";import{createPartFromBase64 as po,createPartFromText as mo}from"@google/genai";var jt=class{constructor(e){this.bucket=new fo().bucket(e)}async saveArtifact(e){let t=await this.listVersions(e),o=t.length>0?Math.max(...t)+1:0,r=this.bucket.file(Ce({...e,version:o}));if(e.artifact.inlineData)return await r.save(JSON.stringify(e.artifact.inlineData.data),{contentType:e.artifact.inlineData.mimeType}),o;if(e.artifact.text)return await r.save(e.artifact.text,{contentType:"text/plain"}),o;throw new Error("Artifact must have either inlineData or text.")}async loadArtifact(e){let t=e.version;if(t===void 0){let s=await this.listVersions(e);if(s.length===0)return;t=Math.max(...s)}let o=this.bucket.file(Ce({...e,version:t})),[[r],[i]]=await Promise.all([o.getMetadata(),o.download()]);return r.contentType==="text/plain"?mo(i.toString("utf-8")):po(i.toString("base64"),r.contentType)}async listArtifactKeys(e){let t=[],o=`${e.appName}/${e.userId}/${e.sessionId}/`,r=`${e.appName}/${e.userId}/user/`,[[i],[s]]=await Promise.all([this.bucket.getFiles({prefix:o}),this.bucket.getFiles({prefix:r})]);for(let a of i)t.push(a.name.split("/").pop());for(let a of s)t.push(a.name.split("/").pop());return t.sort((a,c)=>a.localeCompare(c))}async deleteArtifact(e){let t=await this.listVersions(e);await Promise.all(t.map(o=>this.bucket.file(Ce({...e,version:o})).delete()))}async listVersions(e){let t=Ce(e),[o]=await this.bucket.getFiles({prefix:t}),r=[];for(let i of o){let s=i.name.split("/").pop();r.push(parseInt(s,10))}return r}};function Ce({appName:n,userId:e,sessionId:t,filename:o,version:r}){return o.startsWith("user:")?`${n}/${e}/user/${o}/${r}`:`${n}/${e}/${t}/${o}/${r}`}var Fe=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};import{context as rn,trace as sn}from"@opentelemetry/api";function P(n={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...n}}function Vt(n,e){let t=P();e&&Object.assign(t,e);for(let o of n)o&&(o.stateDelta&&Object.assign(t.stateDelta,o.stateDelta),o.artifactDelta&&Object.assign(t.artifactDelta,o.artifactDelta),o.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,o.requestedAuthConfigs),o.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,o.requestedToolConfirmations),o.skipSummarization!==void 0&&(t.skipSummarization=o.skipSummarization),o.transferToAgent!==void 0&&(t.transferToAgent=o.transferToAgent),o.escalate!==void 0&&(t.escalate=o.escalate));return t}function v(n={}){return{...n,id:n.id||De(),invocationId:n.invocationId||"",author:n.author,actions:n.actions||P(),longRunningToolIds:n.longRunningToolIds||[],branch:n.branch,timestamp:n.timestamp||Date.now()}}function Z(n){return n.actions.skipSummarization||n.longRunningToolIds&&n.longRunningToolIds.length>0?!0:E(n).length===0&&S(n).length===0&&!n.partial&&!Jt(n)}function E(n){let e=[];if(n.content&&n.content.parts)for(let t of n.content.parts)t.functionCall&&e.push(t.functionCall);return e}function S(n){let e=[];if(n.content&&n.content.parts)for(let t of n.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function Jt(n){var e;return n.content&&((e=n.content.parts)!=null&&e.length)?n.content.parts[n.content.parts.length-1].codeExecutionResult!==void 0:!1}function go(n){var e;return(e=n.content)!=null&&e.parts?n.content.parts.map(t=>{var o;return(o=t.text)!=null?o:""}).join(""):""}var Kt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function De(){let n="";for(let e=0;e<8;e++)n+=Kt[Math.floor(Math.random()*Kt.length)];return n}import{context as Ge,trace as se}from"@opentelemetry/api";var oe="0.3.0";var ho="gen_ai.agent.description",Co="gen_ai.agent.name",vo="gen_ai.conversation.id",$e="gen_ai.operation.name",Yt="gen_ai.tool.call.id",Zt="gen_ai.tool.description",Ht="gen_ai.tool.name",xo="gen_ai.tool.type",k=se.getTracer("gcp.vertex.agent",oe);function re(n){try{return JSON.stringify(n)}catch{return"<not serializable>"}}function Wt({agent:n,invocationContext:e}){let t=se.getActiveSpan();t&&t.setAttributes({[$e]:"invoke_agent",[ho]:n.description,[Co]:n.name,[vo]:e.session.id})}function Xt({tool:n,args:e,functionResponseEvent:t}){var s,a;let o=se.getActiveSpan();if(!o)return;o.setAttributes({[$e]:"execute_tool",[Zt]:n.description||"",[Ht]:n.name,[xo]:n.constructor.name,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}","gcp.vertex.agent.tool_call_args":ie()?re(e):"{}"});let r="<not specified>",i="<not specified>";if((s=t.content)!=null&&s.parts){let l=(a=t.content.parts[0])==null?void 0:a.functionResponse;l!=null&&l.id&&(r=l.id),l!=null&&l.response&&(i=l.response)}(typeof i!="object"||i===null)&&(i={result:i}),o.setAttributes({[Yt]:r,"gcp.vertex.agent.event_id":t.id,"gcp.vertex.agent.tool_response":ie()?re(i):"{}"})}function Qt({responseEventId:n,functionResponseEvent:e}){let t=se.getActiveSpan();t&&(t.setAttributes({[$e]:"execute_tool",[Ht]:"(merged tools)",[Zt]:"(merged tools)",[Yt]:n,"gcp.vertex.agent.tool_call_args":"N/A","gcp.vertex.agent.event_id":n,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}"}),t.setAttribute("gcp.vertex.agent.tool_response",ie()?re(e):"{}"))}function en({invocationContext:n,eventId:e,llmRequest:t,llmResponse:o}){var i,s,a;let r=se.getActiveSpan();if(r&&(r.setAttributes({"gen_ai.system":"gcp.vertex.agent","gen_ai.request.model":t.model,"gcp.vertex.agent.invocation_id":n.invocationId,"gcp.vertex.agent.session_id":n.session.id,"gcp.vertex.agent.event_id":e,"gcp.vertex.agent.llm_request":ie()?re(Ao(t)):"{}"}),(i=t.config)!=null&&i.topP&&r.setAttribute("gen_ai.request.top_p",t.config.topP),((s=t.config)==null?void 0:s.maxOutputTokens)!==void 0&&r.setAttribute("gen_ai.request.max_tokens",t.config.maxOutputTokens),r.setAttribute("gcp.vertex.agent.llm_response",ie()?re(o):"{}"),o.usageMetadata&&r.setAttribute("gen_ai.usage.input_tokens",o.usageMetadata.promptTokenCount||0),(a=o.usageMetadata)!=null&&a.candidatesTokenCount&&r.setAttribute("gen_ai.usage.output_tokens",o.usageMetadata.candidatesTokenCount),o.finishReason)){let c=typeof o.finishReason=="string"?o.finishReason.toLowerCase():String(o.finishReason).toLowerCase();r.setAttribute("gen_ai.response.finish_reasons",[c])}}function Ao(n){let e={model:n.model,contents:[]};if(n.config){let{responseSchema:t,...o}=n.config;e.config=o}return e.contents=n.contents.map(t=>{var o;return{role:t.role,parts:((o=t.parts)==null?void 0:o.filter(r=>!r.inlineData))||[]}}),e}function tn(n,e){return{next:Ge.bind(n,e.next.bind(e)),return:Ge.bind(n,e.return.bind(e)),throw:Ge.bind(n,e.throw.bind(e)),[Symbol.asyncIterator](){return tn(n,e[Symbol.asyncIterator]())}}}function D(n,e,t){let o=t.call(e);return tn(n,o)}function ie(){let n=process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS||"true";return n==="true"||n==="1"}var C=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};C.APP_PREFIX="app:",C.USER_PREFIX="user:",C.TEMP_PREFIX="temp:";var T=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new C(this.invocationContext.session.state,{})}};var R=class extends T{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||P(),this._state=new C(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let o=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=o,o}};function xe(){return typeof window<"u"}var ve="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function H(){let n="";for(let e=0;e<ve.length;e++){let t=Math.random()*16|0;ve[e]==="x"?n+=t.toString(16):ve[e]==="y"?n+=(t&3|8).toString(16):n+=ve[e]}return n}function nn(n){return xe()?window.atob(n):Buffer.from(n,"base64").toString()}var qe=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},M=class{constructor(e){this.invocationCostManager=new qe;this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.invocationId=e.invocationId,this.branch=e.branch,this.agent=e.agent,this.userContent=e.userContent,this.session=e.session,this.endInvocation=e.endInvocation||!1,this.transcriptionCache=e.transcriptionCache,this.runConfig=e.runConfig,this.liveRequestQueue=e.liveRequestQueue,this.activeStreamingTools=e.activeStreamingTools,this.pluginManager=e.pluginManager}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function on(){return`e-${H()}`}var Ue=Symbol.for("google.adk.baseAgent");function yo(n){return typeof n=="object"&&n!==null&&Ue in n&&n[Ue]===!0}var cn;cn=Ue;var w=class{constructor(e){this[cn]=!0;this.name=Eo(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.beforeAgentCallback=an(e.beforeAgentCallback),this.afterAgentCallback=an(e.afterAgentCallback),this.setParentAgentForSubAgents()}get rootAgent(){return bo(this)}async*runAsync(e){let t=k.startSpan(`invoke_agent ${this.name}`),o=sn.setSpan(rn.active(),t);try{yield*D(o,this,async function*(){let r=this.createInvocationContext(e),i=await this.handleBeforeAgentCallback(r);if(i&&(yield i),r.endInvocation)return;Wt({agent:this,invocationContext:r});for await(let a of this.runAsyncImpl(r))yield a;if(r.endInvocation)return;let s=await this.handleAfterAgentCallback(r);s&&(yield s)})}finally{t.end()}}async*runLive(e){let t=k.startSpan(`invoke_agent ${this.name}`),o=sn.setSpan(rn.active(),t);try{throw yield*D(o,this,async function*(){}),new Error("Live mode is not implemented yet.")}finally{t.end()}}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let o=t.findAgent(e);if(o)return o}}createInvocationContext(e){return new M({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new R({invocationContext:e});for(let o of this.beforeAgentCallback){let r=await o(t);if(r)return e.endInvocation=!0,v({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return v({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new R({invocationContext:e});for(let o of this.afterAgentCallback){let r=await o(t);if(r)return v({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return v({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function Eo(n){if(!To(n))throw new Error(`Found invalid agent name: "${n}". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.`);if(n==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return n}function To(n){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(n)}function bo(n){for(;n.parentAgent;)n=n.parentAgent;return n}function an(n){return n?Array.isArray(n)?n:[n]:[]}var L=class{},ze=class{};import{createUserContent as Lo}from"@google/genai";import{isEmpty as un}from"lodash-es";var ae=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,o;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((o=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&o.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error(`Auth Scheme ${e} requires authCredential.`);if(!this.authConfig.rawAuthCredential.oauth2)throw new Error(`Auth Scheme ${e} requires oauth2 in authCredential.`);if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error(`Auth Scheme ${e} requires both clientId and clientSecret in authCredential.oauth2.`);return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var G=class{constructor({hint:e,confirmed:t,payload:o}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=o}};var F=class extends R{constructor(e){super(e),this.functionCallId=e.functionCallId,this.toolConfirmation=e.toolConfirmation}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new ae(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new ae(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new G({hint:e,confirmed:!1,payload:t})}};var ln=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(ln||{}),W=1;function So(n){W=n}var je=class{log(e,...t){if(!(e<W))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error(`Unsupported log level: ${e}`)}}debug(...e){W>0||console.debug(Ae(0),...e)}info(...e){W>1||console.info(Ae(1),...e)}warn(...e){W>2||console.warn(Ae(2),...e)}error(...e){W>3||console.error(Ae(3),...e)}},Ve=class{log(e,...t){}debug(...e){}info(...e){}warn(...e){}error(...e){}},Ro={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},Io={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},wo="\x1B[0m";function Ae(n){return`${Io[n]}[ADK ${Ro[n]}]:${wo}`}var $=new je;function Po(n){$=n!=null?n:new Ve}function ko(){return $}var g={log(n,...e){$.log(n,...e)},debug(...n){$.debug(...n)},info(...n){$.info(...n)},warn(...n){$.warn(...n)},error(...n){$.error(...n)}};var Ke="adk-",ye="adk_request_credential",X="adk_request_confirmation",_o={handleFunctionCallList:Ee,generateAuthEvent:Ye,generateRequestConfirmationEvent:Ze};function Je(){return`${Ke}${H()}`}function fn(n){let e=E(n);if(e)for(let t of e)t.id||(t.id=Je())}function dn(n){if(n&&n.parts)for(let e of n.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Ke)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Ke)&&(e.functionResponse.id=void 0)}function pn(n,e){let t=new Set;for(let o of n)o.name&&o.name in e&&e[o.name].isLongRunning&&o.id&&t.add(o.id);return t}function Ye(n,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||un(e.actions.requestedAuthConfigs))return;let t=[],o=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:ye,args:{function_call_id:i,auth_config:s},id:Je()};o.add(a.id),t.push({functionCall:a})}return v({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(o)})}function Ze({invocationContext:n,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||un(t.actions.requestedToolConfirmations))return;let o=[],r=new Set,i=E(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let u=(a=i.find(d=>d.id===c))!=null?a:void 0;if(!u)continue;let f={name:X,args:{originalFunctionCall:u,toolConfirmation:l},id:Je()};r.add(f.id),o.push({functionCall:f})}return v({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:o,role:t.content.role},longRunningToolIds:Array.from(r)})}async function Oo(n,e,t){return k.startActiveSpan(`execute_tool ${n.name}`,async o=>{try{g.debug(`callToolAsync ${n.name}`);let r=await n.runAsync({args:e,toolContext:t});return Xt({tool:n,args:e,functionResponseEvent:Mo(n,r,t,t.invocationContext)}),r}finally{o.end()}})}function Mo(n,e,t,o){let r;typeof e!="object"||e==null?r={result:e}:r=e;let s={role:"user",parts:[{functionResponse:{name:n.name,response:r,id:t.functionCallId}}]};return v({invocationId:o.invocationId,author:o.agent.name,content:s,actions:t.actions,branch:o.branch})}async function mn({invocationContext:n,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=E(e);return await Ee({invocationContext:n,functionCalls:a,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Ee({invocationContext:n,functionCalls:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var u;let a=[],c=e.filter(f=>!i||f.id&&i.has(f.id));for(let f of c){let d;s&&f.id&&(d=s[f.id]);let{tool:m,toolContext:p}=Bo({invocationContext:n,functionCall:f,toolsDict:t,toolConfirmation:d});g.debug(`execute_tool ${m.name}`);let x=(u=f.args)!=null?u:{},h=null,y;if(h=await n.pluginManager.runBeforeToolCallback({tool:m,toolArgs:x,toolContext:p}),h==null){for(let N of o)if(h=await N({tool:m,args:x,context:p}),h)break}if(h==null)try{h=await Oo(m,x,p)}catch(N){if(N instanceof Error){let zt=await n.pluginManager.runOnToolErrorCallback({tool:m,toolArgs:x,toolContext:p,error:N});zt?h=zt:y=N.message}else y=N}let O=await n.pluginManager.runAfterToolCallback({tool:m,toolArgs:x,toolContext:p,result:h});if(O==null){for(let N of r)if(O=await N({tool:m,args:x,context:p,response:h}),O)break}if(O!=null&&(h=O),m.isLongRunning&&!h)continue;y?h={error:y}:(typeof h!="object"||h==null)&&(h={result:h});let Ut=v({invocationId:n.invocationId,author:n.agent.name,content:Lo({functionResponse:{id:p.functionCallId,name:m.name,response:h}}),actions:p.actions,branch:n.branch});g.debug("traceToolCall",{tool:m.name,args:x,functionResponseEvent:Ut.id}),a.push(Ut)}if(!a.length)return null;let l=No(a);return a.length>1&&k.startActiveSpan("execute_tool (merged)",f=>{try{g.debug("execute_tool (merged)"),g.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id}),Qt({responseEventId:l.id,functionResponseEvent:l})}finally{f.end()}}),l}function Bo({invocationContext:n,functionCall:e,toolsDict:t,toolConfirmation:o}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new F({invocationContext:n,functionCallId:e.id||void 0,toolConfirmation:o});return{tool:t[e.name],toolContext:r}}function No(n){if(!n.length)throw new Error("No function response events provided.");if(n.length===1)return n[0];let e=[];for(let i of n)i.content&&i.content.parts&&e.push(...i.content.parts);let t=n[0],o=n.map(i=>i.actions||{}),r=Vt(o);return v({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var He=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),o=this.queue.shift();t(o)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};import{context as gr,trace as hr}from"@opentelemetry/api";import{cloneDeep as $n}from"lodash-es";import{z as qn}from"zod";var We=Symbol.for("google.adk.baseCodeExecutor");function Te(n){return typeof n=="object"&&n!==null&&We in n&&n[We]===!0}var gn;gn=We;var ce=class{constructor(){this[gn]=!0;this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var Fo="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Xe(n){let e=n.match(Fo);return e?e[1]:n}function hn(n){return Xe(n).startsWith("gemini-")}function Do(n){if(!/^\d+(\.\d+)*$/.test(n))return{valid:!1,major:0,minor:0,patch:0};let e=n.split(".").map(t=>parseInt(t,10));return{valid:!0,major:e[0],minor:e.length>1?e[1]:0,patch:e.length>2?e[2]:0}}function Cn(n){return Xe(n).startsWith("gemini-1")}function le(n){if(!n)return!1;let e=Xe(n);if(!e.startsWith("gemini-"))return!1;let t=e.slice(7).split("-",1)[0],o=Do(t);return o.valid&&o.major>=2}var Qe=Symbol.for("google.adk.builtInCodeExecutor");function fe(n){return typeof n=="object"&&n!==null&&Qe in n&&n[Qe]===!0}var vn,xn,ue=class extends(xn=ce,vn=Qe,xn){constructor(){super(...arguments);this[vn]=!0}executeCode(t){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(t){if(t.model&&le(t.model)){t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({codeExecution:{}});return}throw new Error(`Gemini code execution tool is not supported for model ${t.model}`)}};import{Language as Go,Outcome as An}from"@google/genai";import{cloneDeep as $o}from"lodash-es";function yn(n,e){var u;if(!((u=n.parts)!=null&&u.length))return"";for(let f=0;f<n.parts.length;f++){let d=n.parts[f];if(d.executableCode&&(f===n.parts.length-1||!n.parts[f+1].codeExecutionResult))return n.parts=n.parts.slice(0,f+1),d.executableCode.code}let t=n.parts.filter(f=>f.text);if(!t.length)return"";let o=$o(t[0]),r=t.map(f=>f.text).join(`
|
|
8
|
-
`),i=e.map(f=>f[0]).join("|"),s=e.map(f=>f[1]).join("|"),a=new RegExp(`?<prefix>.*?)(${i})(?<codeStr>.*?)(${s})(?<suffix>.*?)$`,"s").exec(r),{prefix:c,codeStr:l}=(a==null?void 0:a.groups)||{};return l?(n.parts=[],c&&(o.text=c,n.parts.push(o)),n.parts.push(et(l)),l):""}function et(n){return{text:n,executableCode:{code:n,language:Go.PYTHON}}}function En(n){if(n.stderr)return{text:n.stderr,codeExecutionResult:{outcome:An.OUTCOME_FAILED}};let e=[];return(n.stdout||!n.outputFiles)&&e.push(`Code execution result:
|
|
9
|
-
${n.stdout}
|
|
10
|
-
`),n.outputFiles&&e.push(`Saved artifacts:
|
|
11
|
-
`+n.outputFiles.map(t=>t.name).join(", ")),{text:e.join(`
|
|
12
|
-
|
|
13
|
-
`),codeExecutionResult:{outcome:An.OUTCOME_OK}}}function Tn(n,e,t){var r;if(!((r=n.parts)!=null&&r.length))return;let o=n.parts[n.parts.length-1];o.executableCode?n.parts[n.parts.length-1]={text:e[0]+o.executableCode.code+e[1]}:n.parts.length==1&&o.codeExecutionResult&&(n.parts[n.parts.length-1]={text:t[0]+o.codeExecutionResult.output+t[1]},n.role="user")}import{cloneDeep as qo}from"lodash-es";var tt="_code_execution_context",nt="execution_session_id",q="processed_input_files",U="_code_executor_input_files",z="_code_executor_error_counts",ot="_code_execution_results",de=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(tt))!=null?t:{},this.sessionState=e}getStateDelta(){return{[tt]:qo(this.context)}}getExecutionId(){if(nt in this.context)return this.context[nt]}setExecutionId(e){this.context[nt]=e}getProcessedFileNames(){return q in this.context?this.context[q]:[]}addProcessedFileNames(e){q in this.context||(this.context[q]=[]),this.context[q].push(...e)}getInputFiles(){return U in this.sessionState?this.sessionState.get(U):[]}addInputFiles(e){U in this.sessionState||this.sessionState.set(U,[]),this.sessionState.get(U).push(...e)}clearInputFiles(){U in this.sessionState&&this.sessionState.set(U,[]),q in this.context&&(this.context[q]=[])}getErrorCount(e){return z in this.sessionState&&this.sessionState.get(z)[e]||0}incrementErrorCount(e){z in this.sessionState||this.sessionState.set(z,{}),this.sessionState.get(z)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(z in this.sessionState))return;let t=this.sessionState.get(z);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:o,resultStderr:r}){ot in this.sessionState||this.sessionState.set(ot,{});let i=this.sessionState.get(ot);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:o,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(){return this.sessionState.get(tt)||{}}};var Uo="google-adk",zo="gl-typescript",jo="remote_reasoning_engine",Vo="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Ko(){let n=`${Uo}/${oe}`;!xe()&&process.env[Vo]&&(n=`${n}+${jo}`);let e=`${zo}/${xe()?window.navigator.userAgent:process.version}`;return[n,e]}function bn(){return Ko()}var rt=Symbol.for("google.adk.baseModel");function it(n){return typeof n=="object"&&n!==null&&rt in n&&n[rt]===!0}var Sn;Sn=rt;var Q=class{constructor({model:e}){this[Sn]=!0;this.model=e}get trackingHeaders(){let t=bn().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};Q.supportedModels=[];function pe(n,e){n.config||(n.config={});let t=e.join(`
|
|
14
|
-
|
|
15
|
-
`);n.config.systemInstruction?n.config.systemInstruction+=`
|
|
16
|
-
|
|
17
|
-
`+t:n.config.systemInstruction=t}function Rn(n,e){n.config||(n.config={}),n.config.responseSchema=e,n.config.responseMimeType="application/json"}import{createPartFromText as wn,FinishReason as Yo,GoogleGenAI as at}from"@google/genai";var be=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(be||{});function In(){return Jo("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Jo(n){if(!process.env)return!1;let e=(process.env[n]||"").toLowerCase();return["true","1"].includes(e)}var Se=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(o=>{var r;return o.parts&&((r=o.parts[0])==null?void 0:r.text)});t.length>0?this.geminiSession.sendClientContent({turns:t,turnComplete:t[t.length-1].role==="user"}):g.info("no content is sent")}async sendContent(e){if(!e.parts)throw new Error("Content must have parts.");if(e.parts[0].functionResponse){let t=e.parts.map(o=>o.functionResponse).filter(o=>!!o);g.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else g.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){g.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};function st(n){var t;let e=n.usageMetadata;if(n.candidates&&n.candidates.length>0){let o=n.candidates[0];return(t=o.content)!=null&&t.parts&&o.content.parts.length>0?{content:o.content,groundingMetadata:o.groundingMetadata,usageMetadata:e,finishReason:o.finishReason}:{errorCode:o.finishReason,errorMessage:o.finishMessage,usageMetadata:e,finishReason:o.finishReason}}return n.promptFeedback?{errorCode:n.promptFeedback.blockReason,errorMessage:n.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var ee=class extends Q{constructor({model:e,apiKey:t,vertexai:o,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s;let a=typeof process=="object";if(this.vertexai=!!o,!this.vertexai&&a){let c=process.env.GOOGLE_GENAI_USE_VERTEXAI;c&&(this.vertexai=c.toLowerCase()==="true"||c==="1")}if(this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}async*generateContentAsync(e,t=!1){var o,r,i,s,a,c,l;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),g.info(`Sending out request, model: ${e.model}, backend: ${this.apiBackend}, stream: ${t}`),(o=e.config)!=null&&o.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let u=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),f="",d="",m,p;for await(let x of u){p=x;let h=st(x);m=h.usageMetadata;let y=(s=(i=h.content)==null?void 0:i.parts)==null?void 0:s[0];if(y!=null&&y.text)"thought"in y&&y.thought?f+=y.text:d+=y.text,h.partial=!0;else if((f||d)&&(!y||!y.inlineData)){let O=[];f&&O.push({text:f,thought:!0}),d&&O.push(wn(d)),yield{content:{role:"model",parts:O},usageMetadata:h.usageMetadata},f="",d=""}yield h}if((d||f)&&((c=(a=p==null?void 0:p.candidates)==null?void 0:a[0])==null?void 0:c.finishReason)===Yo.STOP){let x=[];f&&x.push({text:f,thought:!0}),d&&x.push({text:d}),yield{content:{role:"model",parts:x},usageMetadata:m}}}else{let u=await this.apiClient.models.generateContent({model:(l=e.model)!=null?l:this.model,contents:e.contents,config:e.config});yield st(u)}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};return this.vertexai?this._apiClient=new at({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}}):this._apiClient=new at({apiKey:this.apiKey,httpOptions:{headers:e}}),this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new at({apiKey:this.apiKey,httpOptions:{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}})),this._liveApiClient}async connect(e){var o,r,i,s;(o=e.liveConnectConfig)!=null&&o.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[wn(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new Se(t)}preprocessRequest(e){if(this.apiBackend==="GEMINI_API"&&(e.config&&(e.config.labels=void 0),e.contents)){for(let t of e.contents)if(t.parts)for(let o of t.parts)Pn(o.inlineData),Pn(o.fileData)}}};ee.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function Pn(n){n&&n.displayName&&(n.displayName=void 0)}var ct=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}},I=class I{static newLlm(e){return new(I.resolve(e))({model:e})}static _register(e,t){I.llmRegistryDict.has(e)&&g.info(`Updating LLM class for ${e} from ${I.llmRegistryDict.get(e)} to ${t}`),I.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)I._register(t,e)}static resolve(e){let t=I.resolveCache.get(e);if(t)return t;for(let[o,r]of I.llmRegistryDict.entries())if(new RegExp(`^${o instanceof RegExp?o.source:o}$`,o instanceof RegExp?o.flags:void 0).test(e))return I.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};I.llmRegistryDict=new Map,I.resolveCache=new ct(32);var te=I;te.register(ee);var lt=Symbol.for("google.adk.baseTool");function Zo(n){return typeof n=="object"&&n!==null&< in n&&n[lt]===!0}var kn;kn=lt;var b=class{constructor(e){this[kn]=!0;var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({llmRequest:e}){let t=this._getDeclaration();if(!t)return;e.toolsDict[this.name]=this;let o=Ho(e);o?(o.functionDeclarations||(o.functionDeclarations=[]),o.functionDeclarations.push(t)):(e.config=e.config||{},e.config.tools=e.config.tools||[],e.config.tools.push({functionDeclarations:[t]}))}get apiVariant(){return In()}};function Ho(n){var e;return(((e=n.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as nr}from"@google/genai";import{Type as Ln}from"@google/genai";import{zodToJsonSchema as Wo}from"zod-to-json-schema";import{toJSONSchema as Xo}from"zod/v4";function ut(n){return n!==null&&typeof n=="object"&&"parse"in n&&typeof n.parse=="function"&&"safeParse"in n&&typeof n.safeParse=="function"}function Qo(n){return ut(n)&&!("_zod"in n)}function er(n){return ut(n)&&"_zod"in n}function tr(n){var o,r;let e=n;if((o=e._def)!=null&&o.typeName)return e._def.typeName;let t=(r=e._def)==null?void 0:r.type;if(typeof t=="string"&&t)return"Zod"+t.charAt(0).toUpperCase()+t.slice(1)}function Re(n){return ut(n)&&tr(n)==="ZodObject"}function ft(n){if(!Re(n))throw new Error("Expected a Zod Object");if(er(n))return Xo(n,{target:"openapi-3.0",io:"input",override:e=>{var o;let{jsonSchema:t}=e;t.additionalProperties!==void 0&&delete t.additionalProperties,t.readOnly!==void 0&&delete t.readOnly,t.maxItems!==void 0&&(t.maxItems=t.maxItems.toString()),(t.format==="email"||t.format==="uuid")&&delete t.pattern,t.minItems!==void 0&&(t.minItems=t.minItems.toString()),t.minLength!==void 0&&(t.minLength=t.minLength.toString()),t.maxLength!==void 0&&(t.maxLength=t.maxLength.toString()),((o=t.enum)==null?void 0:o.length)===1&&t.enum[0]===null&&(t.type=Ln.NULL,delete t.enum),t.type!==void 0&&(t.type=t.type.toUpperCase())}});if(Qo(n))return Wo(n,{target:"openApi3",emailStrategy:"format:email",postProcess:e=>{var t,o,r,i,s,a,c;if(e)return e.additionalProperties!==void 0&&delete e.additionalProperties,e.maxItems!==void 0&&(e.maxItems=(t=e.maxItems)==null?void 0:t.toString()),e.minItems!==void 0&&(e.minItems=(o=e.minItems)==null?void 0:o.toString()),e.minLength!==void 0&&(e.minLength=(r=e.minLength)==null?void 0:r.toString()),e.maxLength!==void 0&&(e.maxLength=(i=e.maxLength)==null?void 0:i.toString()),((s=e.enum)==null?void 0:s.length)===1&&e.enum[0]==="null"&&(e.type=Ln.NULL,delete e.enum),e.type==="integer"&&e.format!=="int64"&&((a=e.minimum)!=null||(e.minimum=Number.MIN_SAFE_INTEGER),(c=e.maximum)!=null||(e.maximum=Number.MAX_SAFE_INTEGER)),e.type!==void 0&&(e.type=e.type.toUpperCase()),e}});throw new Error("Unsupported Zod schema version.")}function or(n){return n===void 0?{type:nr.OBJECT,properties:{}}:Re(n)?ft(n):n}var dt=Symbol.for("google.adk.functionTool");function rr(n){return typeof n=="object"&&n!==null&&dt in n&&n[dt]===!0}var _n,On,B=class extends(On=b,_n=dt,On){constructor(t){var r;let o=(r=t.name)!=null?r:t.execute.name;if(!o)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:o,description:t.description,isLongRunning:t.isLongRunning});this[_n]=!0;this.execute=t.execute,this.parameters=t.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:or(this.parameters)}}async runAsync(t){try{let o=t.args;return Re(this.parameters)&&(o=this.parameters.parse(t.args)),await this.execute(o,t.toolContext)}catch(o){let r=o instanceof Error?o.message:String(o);throw new Error(`Error in tool '${this.name}': ${r}`)}}};import{cloneDeep as ir}from"lodash-es";function pt(n,e,t){var s,a,c;let o=[];for(let l of n)!((s=l.content)!=null&&s.role)||((c=(a=l.content.parts)==null?void 0:a[0])==null?void 0:c.text)===""||t&&l.branch&&!t.startsWith(l.branch)||sr(l)||ar(l)||o.push(Nn(e,l)?cr(l):l);let r=lr(o);r=ur(r);let i=[];for(let l of r){let u=ir(l.content);dn(u),i.push(u)}return i}function Bn(n,e,t){for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.author==="user"||Nn(e,r))return pt(n.slice(o),e,t)}return[]}function sr(n){var e,t,o;if(!((e=n.content)!=null&&e.parts))return!1;for(let r of n.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===ye||((o=r.functionResponse)==null?void 0:o.name)===ye)return!0;return!1}function ar(n){var e,t,o;if(!((e=n.content)!=null&&e.parts))return!1;for(let r of n.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===X||((o=r.functionResponse)==null?void 0:o.name)===X)return!0;return!1}function Nn(n,e){return!!n&&e.author!==n&&e.author!=="user"}function cr(n){var t,o,r,i,s,a;if(!((o=(t=n.content)==null?void 0:t.parts)!=null&&o.length))return n;let e={role:"user",parts:[{text:"For context:"}]};for(let c of n.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:`[${n.author}] said: ${c.text}`});else if(c.functionCall){let l=Mn(c.functionCall.args);(i=e.parts)==null||i.push({text:`[${n.author}] called tool \`${c.functionCall.name}\` with parameters: ${l}`})}else if(c.functionResponse){let l=Mn(c.functionResponse.response);(s=e.parts)==null||s.push({text:`[${n.author}] tool \`${c.functionResponse.name}\` returned result: ${l}`})}else(a=e.parts)==null||a.push(c);return v({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}function Fn(n){var r;if(n.length===0)throw new Error("Cannot merge an empty list of events.");let e=v(n[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let o={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(o[s.functionResponse.id]=i)}for(let i of n.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in o?t[o[a]]=s:(t.push(s),o[a]=t.length-1)}else t.push(s)}return e}function lr(n){if(n.length===0)return n;let e=n[n.length-1],t=S(e);if(!(t!=null&&t.length))return n;let o=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=n.at(-2);if(r){let c=E(r);if(c){for(let l of c)if(l.id&&o.has(l.id))return n}}let i=-1;for(let c=n.length-2;c>=0;c--){let l=n[c],u=E(l);if(u!=null&&u.length){for(let f of u)if(f.id&&o.has(f.id)){i=c;let d=new Set(u.map(p=>p.id).filter(p=>!!p));if(!Array.from(o).every(p=>d.has(p)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(o).join(", ")}`);o=d;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(o).join(", ")}`);let s=[];for(let c=i+1;c<n.length-1;c++){let l=n[c],u=S(l);u&&u.some(f=>f.id&&o.has(f.id))&&s.push(l)}s.push(n[n.length-1]);let a=n.slice(0,i+1);return a.push(Fn(s)),a}function ur(n){let e=new Map;for(let o=0;o<n.length;o++){let r=n[o],i=S(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,o)}let t=[];for(let o of n){if(S(o).length>0)continue;let r=E(o);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(o),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(n[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>n[c]);t.push(Fn(a))}}else t.push(o)}return t}function Mn(n){if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}async function mt(n,e){let t=e.invocationContext;async function o(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),u=l.endsWith("?");if(u&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!d)throw new Error(`Artifact ${f} not found.`);return String(d)}if(!pr(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(u)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=n.matchAll(r);for(let c of a){i.push(n.slice(s,c.index));let l=await o(c);i.push(l),s=c.index+c[0].length}return i.push(n.slice(s)),i.join("")}var fr=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Dn(n){return n===""||n===void 0?!1:fr.test(n)}var dr=[C.APP_PREFIX,C.USER_PREFIX,C.TEMP_PREFIX];function pr(n){let e=n.split(":");return e.length===0||e.length>2?!1:e.length===1?Dn(n):dr.includes(e[0]+":")?Dn(e[1]):!1}var gt=(o=>(o.NONE="none",o.SSE="sse",o.BIDI="bidi",o))(gt||{});function Gn(n={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:mr(n.maxLlmCalls||500),...n}}function mr(n){if(n>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return n<=0&&g.warn("maxLlmCalls is less than or equal to 0. This will result in no enforcement on total number of llm calls that will be made for a run. This may not be ideal, as this could result in a never ending communication between the model and the agent in certain cases."),n}var Un="adk_agent_name";async function zn(n,e){return n instanceof b?[n]:await n.getTools(e)}var ht=class extends L{async*runAsync(e,t){var r;let o=e.agent;A(o)&&(t.model=o.canonicalModel.model,t.config={...(r=o.generateContentConfig)!=null?r:{}},o.outputSchema&&Rn(t,o.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))}},Cr=new ht,Ct=class extends L{async*runAsync(e,t){let o=e.agent,r=[`You are an agent. Your internal name is "${o.name}".`];o.description&&r.push(`The description about you is "${o.description}"`),pe(t,r)}},vr=new Ct,vt=class extends L{async*runAsync(e,t){let o=e.agent;if(!(o instanceof j)||!(o.rootAgent instanceof j))return;let r=o.rootAgent;if(A(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new T(e)),a=i;s&&(a=await mt(i,new T(e))),pe(t,[a])}if(o.instruction){let{instruction:i,requireStateInjection:s}=await o.canonicalInstruction(new T(e)),a=i;s&&(a=await mt(i,new T(e))),pe(t,[a])}}},xr=new vt,xt=class{async*runAsync(e,t){let o=e.agent;!o||!A(o)||(o.includeContents==="default"?t.contents=pt(e.session.events,o.name,e.branch):t.contents=Bn(e.session.events,o.name,e.branch))}},Ar=new xt,At=class extends L{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new B({name:this.toolName,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.",parameters:qn.object({agentName:qn.string().describe("the agent name to transfer to.")}),execute:function(t,o){if(!o)throw new Error("toolContext is required.");return o.actions.transferToAgent=t.agentName,"Transfer queued"}})}async*runAsync(t,o){if(!(t.agent instanceof j))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;pe(o,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new F({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:o})}buildTargetAgentsInfo(t){return`
|
|
18
|
-
Agent name: ${t.name}
|
|
19
|
-
Agent description: ${t.description}
|
|
20
|
-
`}buildTargetAgentsInstructions(t,o){let r=`
|
|
21
|
-
You have a list of other agents to transfer to:
|
|
22
|
-
|
|
23
|
-
${o.map(this.buildTargetAgentsInfo).join(`
|
|
24
|
-
`)}
|
|
25
|
-
|
|
26
|
-
If you are the best to answer the question according to your description, you
|
|
27
|
-
can answer it.
|
|
28
|
-
|
|
29
|
-
If another agent is better for answering the question according to its
|
|
30
|
-
description, call \`${this.toolName}\` function to transfer the
|
|
31
|
-
question to that agent. When transferring, do not generate any text other than
|
|
32
|
-
the function call.
|
|
33
|
-
`;return t.parentAgent&&!t.disallowTransferToParent&&(r+=`
|
|
34
|
-
Your parent agent is ${t.parentAgent.name}. If neither the other agents nor
|
|
35
|
-
you are best for answering the question according to the descriptions, transfer
|
|
36
|
-
to your parent agent.
|
|
37
|
-
`),r}getTransferTargets(t){let o=[];return o.push(...t.subAgents),!t.parentAgent||!A(t.parentAgent)||(t.disallowTransferToParent||o.push(t.parentAgent),t.disallowTransferToPeers||o.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),o}},yr=new At,yt=class extends L{async*runAsync(e){let t=e.agent;if(!A(t))return;let o=e.session.events;if(!o||o.length===0)return;let r={},i=-1;for(let s=o.length-1;s>=0;s--){let a=o[s];if(a.author!=="user")continue;let c=S(a);if(!c)continue;let l=!1;for(let u of c){if(u.name!==X)continue;l=!0;let f=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?f=JSON.parse(u.response.response):u.response&&(f=new G({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&f&&(r[u.id]=f)}if(l){i=s;break}}if(Object.keys(r).length!==0)for(let s=i-1;s>=0;s--){let a=o[s],c=E(a);if(!c)continue;let l={},u={};for(let p of c){if(!p.id||!(p.id in r))continue;let x=p.args;if(!x||!("originalFunctionCall"in x))continue;let h=x.originalFunctionCall;h.id&&(l[h.id]=r[p.id],u[h.id]=h)}if(Object.keys(l).length===0)continue;for(let p=o.length-1;p>i;p--){let x=o[p],h=S(x);if(h){for(let y of h)y.id&&y.id in l&&(delete l[y.id],delete u[y.id]);if(Object.keys(l).length===0)break}}if(Object.keys(l).length===0)continue;let f=await t.canonicalTools(new T(e)),d=Object.fromEntries(f.map(p=>[p.name,p])),m=await Ee({invocationContext:e,functionCalls:Object.values(u),toolsDict:d,beforeToolCallbacks:t.canonicalBeforeToolCallbacks,afterToolCallbacks:t.canonicalAfterToolCallbacks,filters:new Set(Object.keys(l)),toolConfirmationDict:l});m&&(yield m);return}}},Er=new yt,Et=class extends L{async*runAsync(e,t){if(e.agent instanceof j&&e.agent.codeExecutor){for await(let o of br(e,t))yield o;if(Te(e.agent.codeExecutor))for(let o of t.contents){let r=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""];Tn(o,r,e.agent.codeExecutor.executionResultDelimiters)}}}},Ie={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},Tr=`
|
|
38
|
-
import pandas as pd
|
|
39
|
-
|
|
40
|
-
def explore_df(df: pd.DataFrame) -> None:
|
|
41
|
-
"""Prints some information about a pandas DataFrame."""
|
|
42
|
-
|
|
43
|
-
with pd.option_context(
|
|
44
|
-
'display.max_columns', None, 'display.expand_frame_repr', False
|
|
45
|
-
):
|
|
46
|
-
# Print the column names to never encounter KeyError when selecting one.
|
|
47
|
-
df_dtypes = df.dtypes
|
|
48
|
-
|
|
49
|
-
# Obtain information about data types and missing values.
|
|
50
|
-
df_nulls = (len(df) - df.isnull().sum()).apply(
|
|
51
|
-
lambda x: f'{x} / {df.shape[0]} non-null'
|
|
52
|
-
)
|
|
53
|
-
|
|
54
|
-
# Explore unique total values in columns using \`.unique()\`.
|
|
55
|
-
df_unique_count = df.apply(lambda x: len(x.unique()))
|
|
56
|
-
|
|
57
|
-
# Explore unique values in columns using \`.unique()\`.
|
|
58
|
-
df_unique = df.apply(lambda x: crop(str(list(x.unique()))))
|
|
59
|
-
|
|
60
|
-
df_info = pd.concat(
|
|
61
|
-
(
|
|
62
|
-
df_dtypes.rename('Dtype'),
|
|
63
|
-
df_nulls.rename('Non-Null Count'),
|
|
64
|
-
df_unique_count.rename('Unique Values Count'),
|
|
65
|
-
df_unique.rename('Unique Values'),
|
|
66
|
-
),
|
|
67
|
-
axis=1,
|
|
68
|
-
)
|
|
69
|
-
df_info.index.name = 'Columns'
|
|
70
|
-
print(f"""Total rows: {df.shape[0]}
|
|
71
|
-
Total columns: {df.shape[1]}
|
|
72
|
-
|
|
73
|
-
{df_info}""")
|
|
74
|
-
`,Tt=class{async*runAsync(e,t){if(!t.partial)for await(let o of Sr(e,t))yield o}},Ac=new Tt;async function*br(n,e){let t=n.agent;if(!A(t))return;let o=t.codeExecutor;if(!o||!Te(o))return;if(fe(o)){o.processLlmRequest(e);return}if(!o.optimizeDataFile)return;let r=new de(new C(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=Rr(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=Ir(c);if(!l)return;let u={role:"model",parts:[{text:`Processing input file: \`${c.name}\``},et(l)]};e.contents.push($n(u)),yield v({invocationId:n.invocationId,author:t.name,branch:n.branch,content:u});let f=Kn(n,r),d=await o.executeCode({invocationContext:n,codeExecutionInput:{code:l,inputFiles:[c],executionId:f}});r.updateCodeExecutionResult({invocationId:n.invocationId,code:l,resultStdout:d.stdout,resultStderr:d.stderr}),r.addProcessedFileNames([c.name]);let m=await Jn(n,r,d);yield m,e.contents.push($n(m.content))}}async function*Sr(n,e){let t=n.agent;if(!A(t))return;let o=t.codeExecutor;if(!o||!Te(o)||!e||!e.content||fe(o))return;let r=new de(new C(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=e.content,s=yn(i,o.codeBlockDelimiters);if(!s)return;yield v({invocationId:n.invocationId,author:t.name,branch:n.branch,content:i});let a=Kn(n,r),c=await o.executeCode({invocationContext:n,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}});r.updateCodeExecutionResult({invocationId:n.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield await Jn(n,r,c),e.content=void 0}function Rr(n,e){var r;let t=n.getInputFiles(),o=new Set(t.map(i=>i.name));for(let i=0;i<e.contents.length;i++){let s=e.contents[i];if(!(s.role!=="user"||!s.parts))for(let a=0;a<s.parts.length;a++){let c=s.parts[a],l=(r=c.inlineData)==null?void 0:r.mimeType;if(!l||!c.inlineData||!Ie[l])continue;let u=`data_${i+1}_${a+1}${Ie[l].extension}`;c.text=`
|
|
75
|
-
Available file: \`${u}\`
|
|
76
|
-
`;let f={name:u,content:nn(c.inlineData.data),mimeType:l};o.has(u)||(n.addInputFiles([f]),t.push(f))}}return t}function Kn(n,e){var r;let t=n.agent;if(!A(t)||!((r=t.codeExecutor)!=null&&r.stateful))return;let o=e.getExecutionId();return o||(o=n.session.id,e.setExecutionId(o)),o}async function Jn(n,e,t){if(!n.artifactService)throw new Error("Artifact service is not initialized.");let o={role:"model",parts:[En(t)]},r=P({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(n.invocationId):e.resetErrorCount(n.invocationId);for(let i of t.outputFiles){let s=await n.artifactService.saveArtifact({appName:n.appName||"",userId:n.userId||"",sessionId:n.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return v({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:o,actions:r})}function Ir(n){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!Ie[n.mimeType])return;let t=e(n.name),o=Ie[n.mimeType].loaderCodeTemplate.replace("{filename}",n.name);return`
|
|
77
|
-
${Tr}
|
|
78
|
-
|
|
79
|
-
# Load the dataframe.
|
|
80
|
-
${t} = ${o}
|
|
81
|
-
|
|
82
|
-
# Use \`explore_df\` to guide my analysis.
|
|
83
|
-
explore_df(${t})
|
|
84
|
-
`}var wr=new Et,bt=Symbol.for("google.adk.llmAgent");function A(n){return typeof n=="object"&&n!==null&&bt in n&&n[bt]===!0}var jn,Vn,j=class n extends(Vn=w,jn=bt,Vn){constructor(t){var r,i,s,a,c,l,u,f,d;super(t);this[jn]=!0;if(this.model=t.model,this.instruction=(r=t.instruction)!=null?r:"",this.globalInstruction=(i=t.globalInstruction)!=null?i:"",this.tools=(s=t.tools)!=null?s:[],this.generateContentConfig=t.generateContentConfig,this.disallowTransferToParent=(a=t.disallowTransferToParent)!=null?a:!1,this.disallowTransferToPeers=(c=t.disallowTransferToPeers)!=null?c:!1,this.includeContents=(l=t.includeContents)!=null?l:"default",this.inputSchema=t.inputSchema,this.outputSchema=t.outputSchema,this.outputKey=t.outputKey,this.beforeModelCallback=t.beforeModelCallback,this.afterModelCallback=t.afterModelCallback,this.beforeToolCallback=t.beforeToolCallback,this.afterToolCallback=t.afterToolCallback,this.codeExecutor=t.codeExecutor,this.requestProcessors=(u=t.requestProcessors)!=null?u:[Cr,vr,xr,Er,Ar,wr],this.responseProcessors=(f=t.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((d=this.subAgents)!=null&&d.length)||this.requestProcessors.push(yr),t.generateContentConfig){if(t.generateContentConfig.tools)throw new Error("All tools must be set via LlmAgent.tools.");if(t.generateContentConfig.systemInstruction)throw new Error("System instruction must be set via LlmAgent.instruction.");if(t.generateContentConfig.responseSchema)throw new Error("Response schema must be set via LlmAgent.output_schema.")}else this.generateContentConfig={};if(this.outputSchema){if((!this.disallowTransferToParent||!this.disallowTransferToPeers)&&(g.warn(`Invalid config for agent ${this.name}: outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true`),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, subAgents must be empty to disable agent transfer.`);if(this.tools&&this.tools.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, tools must be empty`)}}get canonicalModel(){if(it(this.model))return this.model;if(typeof this.model=="string"&&this.model)return te.newLlm(this.model);let t=this.parentAgent;for(;t;){if(A(t))return t.canonicalModel;t=t.parentAgent}throw new Error(`No model found for ${this.name}.`)}async canonicalInstruction(t){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(t),requireStateInjection:!1}}async canonicalGlobalInstruction(t){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(t),requireStateInjection:!1}}async canonicalTools(t){let o=[];for(let r of this.tools){let i=await zn(r,t);o.push(...i)}return o}static normalizeCallbackArray(t){return t?Array.isArray(t)?t:[t]:[]}get canonicalBeforeModelCallbacks(){return n.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return n.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return n.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return n.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(t){var i,s;if(t.author!==this.name){g.debug(`Skipping output save for agent ${this.name}: event authored by ${t.author}`);return}if(!this.outputKey){g.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!Z(t)){g.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((s=(i=t.content)==null?void 0:i.parts)!=null&&s.length)){g.debug(`Skipping output save for agent ${this.name}: event content is empty`);return}let o=t.content.parts.map(a=>a.text?a.text:"").join(""),r=o;if(this.outputSchema){if(!o.trim())return;try{r=JSON.parse(o)}catch(a){g.error(`Error parsing output for agent ${this.name}`,a)}}t.actions.stateDelta[this.outputKey]=r}async*runAsyncImpl(t){for(;;){let o;for await(let r of this.runOneStepAsync(t))o=r,this.maybeSaveOutputToState(r),yield r;if(!o||Z(o))break;if(o.partial){g.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(t){for await(let o of this.runLiveFlow(t))this.maybeSaveOutputToState(o),yield o;t.endInvocation}async*runLiveFlow(t){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(t){let o={contents:[],toolsDict:{},liveConnectConfig:{}};for(let a of this.requestProcessors)for await(let c of a.runAsync(t,o))yield c;for(let a of this.tools){let c=new F({invocationContext:t}),l=await zn(a,new T(t));for(let u of l)await u.processLlmRequest({toolContext:c,llmRequest:o})}if(t.endInvocation)return;let r=v({invocationId:t.invocationId,author:this.name,branch:t.branch}),i=k.startSpan("call_llm"),s=hr.setSpan(gr.active(),i);yield*D(s,this,async function*(){for await(let a of this.callLlmAsync(t,o,r))for await(let c of this.postprocess(t,o,a,r))r.id=De(),r.timestamp=new Date().getTime(),yield c}),i.end()}async*postprocess(t,o,r,i){var f;for(let d of this.responseProcessors)for await(let m of d.runAsync(t,r))yield m;if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=v({...i,...r});if(s.content){let d=E(s);d!=null&&d.length&&(fn(s),s.longRunningToolIds=Array.from(pn(d,o.toolsDict)))}if(yield s,!((f=E(s))!=null&&f.length))return;let a=await mn({invocationContext:t,functionCallEvent:s,toolsDict:o.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!a)return;let c=Ye(t,a);c&&(yield c);let l=Ze({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});l&&(yield l),yield a;let u=a.actions.transferToAgent;if(u){let d=this.getAgentByName(t,u);for await(let m of d.runAsync(t))yield m}}getAgentByName(t,o){let i=t.agent.rootAgent.findAgent(o);if(!i)throw new Error(`Agent ${o} not found in the agent tree.`);return i}async*callLlmAsync(t,o,r){var a,c,l,u,f;let i=await this.handleBeforeModelCallback(t,o,r);if(i){yield i;return}(a=o.config)!=null||(o.config={}),(l=(c=o.config).labels)!=null||(c.labels={}),o.config.labels[Un]||(o.config.labels[Un]=this.name);let s=this.canonicalModel;if((u=t.runConfig)!=null&&u.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{t.incrementLlmCallCount();let d=s.generateContentAsync(o,((f=t.runConfig)==null?void 0:f.streamingMode)==="sse");for await(let m of this.runAndHandleError(d,t,o,r)){en({invocationContext:t,eventId:r.id,llmRequest:o,llmResponse:m});let p=await this.handleAfterModelCallback(t,m,r);yield p!=null?p:m}}}async handleBeforeModelCallback(t,o,r){let i=new R({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runBeforeModelCallback({callbackContext:i,llmRequest:o});if(s)return s;for(let a of this.canonicalBeforeModelCallbacks){let c=await a({context:i,request:o});if(c)return c}}async handleAfterModelCallback(t,o,r){let i=new R({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runAfterModelCallback({callbackContext:i,llmResponse:o});if(s)return s;for(let a of this.canonicalAfterModelCallbacks){let c=await a({context:i,response:o});if(c)return c}}async*runAndHandleError(t,o,r,i){try{for await(let s of t)yield s}catch(s){let a=new R({invocationContext:o,eventActions:i.actions});if(s instanceof Error){let c=await o.pluginManager.runOnModelErrorCallback({callbackContext:a,llmRequest:r,error:s});if(c)yield c;else{let l=JSON.parse(s.message);yield{errorCode:String(l.error.code),errorMessage:l.error.message}}}else throw g.error("Unknown error during response generation",s),s}}};var St=Symbol.for("google.adk.loopAgent");function Pr(n){return typeof n=="object"&&n!==null&&St in n&&n[St]===!0}var Yn,Zn,Rt=class extends(Zn=w,Yn=St,Zn){constructor(t){var o;super(t);this[Yn]=!0;this.maxIterations=(o=t.maxIterations)!=null?o:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(t){let o=0;for(;o<this.maxIterations;){for(let r of this.subAgents){let i=!1;for await(let s of r.runAsync(t))yield s,s.actions.escalate&&(i=!0);if(i)return}o++}}async*runLiveImpl(t){throw new Error("This is not supported yet for LoopAgent.")}};var It=Symbol.for("google.adk.parallelAgent");function kr(n){return typeof n=="object"&&n!==null&&It in n&&n[It]===!0}var Hn,Wn,wt=class extends(Wn=w,Hn=It,Wn){constructor(){super(...arguments);this[Hn]=!0}async*runAsyncImpl(t){let o=this.subAgents.map(r=>r.runAsync(Lr(this,r,t)));for await(let r of _r(o))yield r}async*runLiveImpl(t){throw new Error("This is not supported yet for ParallelAgent.")}};function Lr(n,e,t){let o=new M(t),r=`${n.name}.${e.name}`;return o.branch=o.branch?`${o.branch}.${r}`:r,o}async function*_r(n){let e=new Map;for(let[t,o]of n.entries()){let r=o.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:o}=await Promise.race(e.values());if(t.done){e.delete(o);continue}yield t.value;let r=n[o].next().then(i=>({result:i,index:o}));e.set(o,r)}}var Pt="task_completed",kt=Symbol.for("google.adk.sequentialAgent");function Or(n){return typeof n=="object"&&n!==null&&kt in n&&n[kt]===!0}var Xn,Qn,Lt=class extends(Qn=w,Xn=kt,Qn){constructor(){super(...arguments);this[Xn]=!0}async*runAsyncImpl(t){for(let o of this.subAgents)for await(let r of o.runAsync(t))yield r}async*runLiveImpl(t){for(let o of this.subAgents)A(o)&&((await o.canonicalTools(new T(t))).some(s=>s.name===Pt)||(o.tools.push(new B({name:Pt,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),o.instruction+=`If you finished the user's request according to its description, call the ${Pt} function to exit so the next agents can take over. When calling this function, do not generate any text other than the function call.`));for(let o of this.subAgents)for await(let r of o.runLive(t))yield r}};var me=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:o,filename:r,artifact:i}){let s=we(e,t,o,r);this.artifacts[s]||(this.artifacts[s]=[]);let a=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(a)}loadArtifact({appName:e,userId:t,sessionId:o,filename:r,version:i}){let s=we(e,t,o,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:o}){let r=`${e}/${t}/${o}/`,i=`${e}/${t}/user/`,s=[];for(let a in this.artifacts)if(a.startsWith(r)){let c=a.replace(r,"");s.push(c)}else if(a.startsWith(i)){let c=a.replace(i,"");s.push(c)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:o,filename:r}){let i=we(e,t,o,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:o,filename:r}){let i=we(e,t,o,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let a=[];for(let c=0;c<s.length;c++)a.push(c);return Promise.resolve(a)}};function we(n,e,t,o){return Mr(o)?`${n}/${e}/user/${o}`:`${n}/${e}/${t}/${o}`}function Mr(n){return n.startsWith("user:")}var eo=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(eo||{});var _t=Symbol.for("google.adk.baseExampleProvider");function Br(n){return typeof n=="object"&&n!==null&&_t in n&&n[_t]===!0}var to;to=_t;var Ot=class{constructor(){this[to]=!0}};var V=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=no(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(o=>{var r,i,s;return((s=(i=(r=o.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=no(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let o=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(d=>d.text).filter(d=>!!d).join(" "),u=Nr(l);if(!u.size)continue;o.some(d=>u.has(d))&&r.memories.push({content:c.content,author:c.author,timestamp:Fr(c.timestamp)})}return r}};function no(n,e){return`${n}/${e}`}function Nr(n){return new Set([...n.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Fr(n){return new Date(n).toISOString()}var K=class{constructor(e){this.name=e}async onUserMessageCallback(e){}async beforeRunCallback(e){}async onEventCallback(e){}async afterRunCallback(e){}async beforeAgentCallback(e){}async afterAgentCallback(e){}async beforeModelCallback(e){}async afterModelCallback(e){}async onModelErrorCallback(e){}async beforeToolCallback(e){}async afterToolCallback(e){}async onToolErrorCallback(e){}};var Mt=class extends K{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var o;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Session ID: ${e.session.id}`),this.log(` User ID: ${e.userId}`),this.log(` App Name: ${e.appName}`),this.log(` Root Agent: ${(o=e.agent.name)!=null?o:"Unknown"}`),this.log(` User Content: ${this.formatContent(t)}`),e.branch&&this.log(` Branch: ${e.branch}`)}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Starting Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async onEventCallback({event:e}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${e.id}`),this.log(` Author: ${e.author}`),this.log(` Content: ${this.formatContent(e.content)}`),this.log(` Final Response: ${Z(e)}`);let t=E(e);if(t.length>0){let r=t.map(i=>i.name);this.log(` Function Calls: ${r}`)}let o=S(e);if(o.length>0){let r=o.map(i=>i.name);this.log(` Function Responses: ${r}`)}e.longRunningToolIds&&e.longRunningToolIds.length>0&&this.log(` Long Running Tools: ${[...e.longRunningToolIds]}`)}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Final Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async beforeAgentCallback({callbackContext:e}){this.log("\u{1F916} AGENT STARTING"),this.log(` Agent Name: ${e.agentName}`),this.log(` Invocation ID: ${e.invocationId}`),e.invocationContext.branch&&this.log(` Branch: ${e.invocationContext.branch}`)}async afterAgentCallback({callbackContext:e}){this.log("\u{1F916} AGENT COMPLETED"),this.log(` Agent Name: ${e.agentName}`),this.log(` Invocation ID: ${e.invocationId}`)}async beforeModelCallback({callbackContext:e,llmRequest:t}){var o;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(` Model: ${(o=t.model)!=null?o:"default"}`),this.log(` Agent: ${e.agentName}`),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(` System Instruction: '${r}'`)}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(` Available Tools: ${r}`)}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(` Agent: ${e.agentName}`),t.errorCode?(this.log(` \u274C ERROR - Code: ${t.errorCode}`),this.log(` Error Message: ${t.errorMessage}`)):(this.log(` Content: ${this.formatContent(t.content)}`),t.partial&&this.log(` Partial: ${t.partial}`),t.turnComplete!==void 0&&this.log(` Turn Complete: ${t.turnComplete}`)),t.usageMetadata&&this.log(` Token Usage - Input: ${t.usageMetadata.promptTokenCount}, Output: ${t.usageMetadata.candidatesTokenCount}`)}async beforeToolCallback({tool:e,toolArgs:t,toolContext:o}){this.log("\u{1F527} TOOL STARTING"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${o.agentName}`),this.log(` Function Call ID: ${o.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`)}async afterToolCallback({tool:e,toolContext:t,result:o}){this.log("\u{1F527} TOOL COMPLETED"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${t.agentName}`),this.log(` Function Call ID: ${t.functionCallId}`),this.log(` Result: ${this.formatArgs(o)}`)}async onModelErrorCallback({callbackContext:e,error:t}){this.log("\u{1F9E0} LLM ERROR"),this.log(` Agent: ${e.agentName}`),this.log(` Error: ${t}`)}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${o.agentName}`),this.log(` Function Call ID: ${o.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`),this.log(` Error: ${r}`)}log(e){let t=`\x1B[90m[${this.name}] ${e}\x1B[0m`;g.info(t)}formatContent(e,t=200){if(!e||!e.parts)return"None";let o=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),o.push(`text: '${i}'`)}else r.functionCall?o.push(`function_call: ${r.functionCall.name}`):r.functionResponse?o.push(`function_response: ${r.functionResponse.name}`):r.codeExecutionResult?o.push("code_execution_result"):o.push("other_part");return o.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let o=JSON.stringify(e);return o.length>t&&(o=o.substring(0,t)+"...}"),o}};var ge=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error(`Plugin '${e.name}' already registered.`);if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error(`Plugin with name '${e.name}' already registered.`);this.plugins.add(e),g.info(`Plugin '${e.name}' registered.`)}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,o){for(let r of e)try{let i=await t(r);if(i!==void 0)return g.debug(`Plugin '${r.name}' returned a value for callback '${o}', exiting early.`),i}catch(i){let s=`Error in plugin '${r.name}' during '${o}' callback: ${i}`;throw g.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,o=>o.onUserMessageCallback({userMessage:e,invocationContext:t}),"onUserMessageCallback")}async runBeforeRunCallback({invocationContext:e}){return await this.runCallbacks(this.plugins,t=>t.beforeRunCallback({invocationContext:e}),"beforeRunCallback")}async runAfterRunCallback({invocationContext:e}){await this.runCallbacks(this.plugins,t=>t.afterRunCallback({invocationContext:e}),"afterRunCallback")}async runOnEventCallback({invocationContext:e,event:t}){return await this.runCallbacks(this.plugins,o=>o.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async runBeforeToolCallback({tool:e,toolArgs:t,toolContext:o}){return await this.runCallbacks(this.plugins,r=>r.beforeToolCallback({tool:e,toolArgs:t,toolContext:o}),"beforeToolCallback")}async runAfterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}){return await this.runCallbacks(this.plugins,i=>i.afterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}),"afterToolCallback")}async runOnModelErrorCallback({callbackContext:e,llmRequest:t,error:o}){return await this.runCallbacks(this.plugins,r=>r.onModelErrorCallback({callbackContext:e,llmRequest:t,error:o}),"onModelErrorCallback")}async runBeforeModelCallback({callbackContext:e,llmRequest:t}){return await this.runCallbacks(this.plugins,o=>o.beforeModelCallback({callbackContext:e,llmRequest:t}),"beforeModelCallback")}async runAfterModelCallback({callbackContext:e,llmResponse:t}){return await this.runCallbacks(this.plugins,o=>o.afterModelCallback({callbackContext:e,llmResponse:t}),"afterModelCallback")}async runOnToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){return await this.runCallbacks(this.plugins,i=>i.onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}),"onToolErrorCallback")}};var ro="adk_request_confirmation",Bt="orcas_tool_call_security_check_states",oo="This tool call needs external confirmation before completion.",io=(o=>(o.DENY="DENY",o.CONFIRM="CONFIRM",o.ALLOW="ALLOW",o))(io||{}),Pe=class{async evaluate(){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Nt=class extends K{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Pe}async beforeToolCallback({tool:e,toolArgs:t,toolContext:o}){let r=this.getToolCallCheckState(o);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:o});if(r==="CONFIRM"){if(!o.toolConfirmation)return{partial:oo};if(this.setToolCallCheckState(o,o.toolConfirmation),!o.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};o.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(Bt))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:o}=e;if(!o)return;let r=(i=e.state.get(Bt))!=null?i:{};r[o]=t,e.state.set(Bt,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:o}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(o,r.outcome),r.outcome){case"DENY":return{error:`This tool call is rejected by policy engine. Reason: ${r.reason}`};case"CONFIRM":return o.requestConfirmation({hint:`Policy engine requires confirmation calling tool: ${e.name}. Reason: ${r.reason}`}),{partial:oo};case"ALLOW":return;default:return}}};function Dr(n){if(!n.content||!n.content.parts)return[];let e=[];for(let t of n.content.parts)t&&t.functionCall&&t.functionCall.name===ro&&e.push(t.functionCall);return e}import{cloneDeep as so}from"lodash-es";var ke=class{async appendEvent({session:e,event:t}){return t.partial||(this.updateSessionState({session:e,event:t}),e.events.push(t)),t}updateSessionState({session:e,event:t}){if(!(!t.actions||!t.actions.stateDelta))for(let[o,r]of Object.entries(t.actions.stateDelta))o.startsWith(C.TEMP_PREFIX)||(e.state[o]=r)}};function Le(n){return{id:n.id,appName:n.appName,userId:n.userId||"",state:n.state||{},events:n.events||[],lastUpdateTime:n.lastUpdateTime||0}}var J=class extends ke{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:o,state:r,sessionId:i}){let s=Le({id:i||H(),appName:t,userId:o,state:r,events:[],lastUpdateTime:Date.now()});return this.sessions[t]||(this.sessions[t]={}),this.sessions[t][o]||(this.sessions[t][o]={}),this.sessions[t][o][s.id]=s,Promise.resolve(this.mergeState(t,o,so(s)))}getSession({appName:t,userId:o,sessionId:r,config:i}){if(!this.sessions[t]||!this.sessions[t][o]||!this.sessions[t][o][r])return Promise.resolve(void 0);let s=this.sessions[t][o][r],a=so(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let c=a.events.length-1;for(;c>=0&&!(a.events[c].timestamp<i.afterTimestamp);)c--;c>=0&&(a.events=a.events.slice(c+1))}return Promise.resolve(this.mergeState(t,o,a))}listSessions({appName:t,userId:o}){if(!this.sessions[t]||!this.sessions[t][o])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][o]))r.push(Le({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:o,sessionId:r}){await this.getSession({appName:t,userId:o,sessionId:r})&&delete this.sessions[t][o][r]}async appendEvent({session:t,event:o}){await super.appendEvent({session:t,event:o}),t.lastUpdateTime=o.timestamp;let r=t.appName,i=t.userId,s=t.id,a=l=>{g.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return a(`appName ${r} not in sessions`),o;if(!this.sessions[r][i])return a(`userId ${i} not in sessions[appName]`),o;if(!this.sessions[r][i][s])return a(`sessionId ${s} not in sessions[appName][userId]`),o;if(o.actions&&o.actions.stateDelta)for(let l of Object.keys(o.actions.stateDelta))l.startsWith(C.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(C.APP_PREFIX,"")]=o.actions.stateDelta[l]),l.startsWith(C.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(C.USER_PREFIX,"")]=o.actions.stateDelta[l]);let c=this.sessions[r][i][s];return await super.appendEvent({session:c,event:o}),c.lastUpdateTime=o.timestamp,o}mergeState(t,o,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[C.APP_PREFIX+i]=this.appState[t][i];if(!this.userState[t]||!this.userState[t][o])return r;for(let i of Object.keys(this.userState[t][o]))r.state[C.USER_PREFIX+i]=this.userState[t][o][i];return r}};import{createPartFromText as Gr}from"@google/genai";import{context as $r,trace as qr}from"@opentelemetry/api";var Y=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ge((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}async*runAsync(e){let{userId:t,sessionId:o,stateDelta:r}=e,i=Gn(e.runConfig),s=e.newMessage,a=k.startSpan("invocation"),c=qr.setSpan($r.active(),a);try{yield*D(c,this,async function*(){var d;let l=await this.sessionService.getSession({appName:this.appName,userId:t,sessionId:o});if(!l)throw this.appName?new Error(`Session not found: ${o}`):new Error("Session lookup failed: appName must be provided in runner constructor");if(i.supportCfc&&A(this.agent)){let m=this.agent.canonicalModel.model;if(!le(m))throw new Error(`CFC is not supported for model: ${m} in agent: ${this.agent.name}`);fe(this.agent.codeExecutor)||(this.agent.codeExecutor=new ue)}let u=new M({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:on(),agent:this.agent,session:l,userContent:s,runConfig:i,pluginManager:this.pluginManager}),f=await this.pluginManager.runOnUserMessageCallback({userMessage:s,invocationContext:u});if(f&&(s=f),s){if(!((d=s.parts)!=null&&d.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(u.invocationId,l.userId,l.id,s),await this.sessionService.appendEvent({session:l,event:v({invocationId:u.invocationId,author:"user",actions:r?P({stateDelta:r}):void 0,content:s})})}if(u.agent=this.determineAgentForResumption(l,this.agent),s){let m=await this.pluginManager.runBeforeRunCallback({invocationContext:u});if(m){let p=v({invocationId:u.invocationId,author:"model",content:m});await this.sessionService.appendEvent({session:l,event:p}),yield p}else{for await(let p of u.agent.runAsync(u)){p.partial||await this.sessionService.appendEvent({session:l,event:p});let x=await this.pluginManager.runOnEventCallback({invocationContext:u,event:p});x?yield x:yield p}await this.pluginManager.runAfterRunCallback({invocationContext:u})}}})}finally{a.end()}}async saveArtifacts(e,t,o,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let c=`artifact_${e}_${s}`;await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:o,filename:c,artifact:a}),r.parts[s]=Gr(`Uploaded file: ${c}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let o=Ur(e.events);if(o&&o.author)return t.findAgent(o.author)||t;for(let r=e.events.length-1;r>=0;r--){g.info("event: ",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){g.warn(`Event from an unknown agent: ${i.author}, event id: ${i.id}`);continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!A(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Ur(n){var o,r,i,s;if(!n.length)return null;let t=(s=(i=(r=(o=n[n.length-1].content)==null?void 0:o.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=n.length-2;a>=0;a--){let c=n[a],l=E(c);if(l){for(let u of l)if(u.id===t)return c}}return null}var Ft=class extends Y{constructor({agent:e,appName:t="InMemoryRunner",plugins:o=[]}){super({appName:t,agent:e,plugins:o,artifactService:new me,sessionService:new J,memoryService:new V})}};import{Type as Oe}from"@google/genai";var _e=class{constructor(e){this.toolContext=e;this.invocationContext=e.invocationContext}async saveArtifact(e){return this.toolContext.saveArtifact(e.filename,e.artifact)}async loadArtifact(e){return this.toolContext.loadArtifact(e.filename,e.version)}async listArtifactKeys(){return this.toolContext.listArtifacts()}async deleteArtifact(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.deleteArtifact(e)}async listVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listVersions(e)}};var Dt=Symbol.for("google.adk.agentTool");function zr(n){return typeof n=="object"&&n!==null&&Dt in n&&n[Dt]===!0}var ao,co,Gt=class extends(co=b,ao=Dt,co){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[ao]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(A(this.agent)&&this.agent.inputSchema?t={name:this.name,description:this.description,parameters:this.agent.inputSchema}:t={name:this.name,description:this.description,parameters:{type:Oe.OBJECT,properties:{request:{type:Oe.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let o=A(this.agent)&&this.agent.outputSchema;t.response=o?{type:Oe.OBJECT}:{type:Oe.STRING}}return t}async runAsync({args:t,toolContext:o}){var f,d;this.skipSummarization&&(o.actions.skipSummarization=!0);let i={role:"user",parts:[{text:A(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new Y({appName:this.agent.name,agent:this.agent,artifactService:new _e(o),sessionService:new J,memoryService:new V,credentialService:o.invocationContext.credentialService}),a=await s.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:o.state.toRecord()}),c;for await(let m of s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i}))m.actions.stateDelta&&o.state.update(m.actions.stateDelta),c=m;if(!((d=(f=c==null?void 0:c.content)==null?void 0:f.parts)!=null&&d.length))return"";let l=A(this.agent)&&this.agent.outputSchema,u=c.content.parts.map(m=>m.text).filter(m=>m).join(`
|
|
85
|
-
`);return l?JSON.parse(u):u}};var he=class{constructor(e){this.toolFilter=e}isToolSelected(e,t){return this.toolFilter?typeof this.toolFilter=="function"?this.toolFilter(e,t):Array.isArray(this.toolFilter)?this.toolFilter.includes(e.name):!1:!0}async processLlmRequest(e,t){}};var Me=class extends b{constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(){return Promise.resolve()}async processLlmRequest({llmRequest:e}){if(e.model){if(e.config=e.config||{},e.config.tools=e.config.tools||[],Cn(e.model)){if(e.config.tools.length>0)throw new Error("Google search tool can not be used with other tools in Gemini 1.x.");e.config.tools.push({googleSearchRetrieval:{}});return}if(hn(e.model)){e.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${e.model}`)}}},jr=new Me;var lo=`
|
|
86
|
-
|
|
87
|
-
NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,$t=class extends B{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=lo:e.description=lo.trimStart(),e}};import{MetricExporter as Vr}from"@google-cloud/opentelemetry-cloud-monitoring-exporter";import{TraceExporter as Kr}from"@google-cloud/opentelemetry-cloud-trace-exporter";import{gcpDetector as Jr}from"@opentelemetry/resource-detector-gcp";import{detectResources as Yr}from"@opentelemetry/resources";import{PeriodicExportingMetricReader as Zr}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as Hr}from"@opentelemetry/sdk-trace-base";import{GoogleAuth as Wr}from"google-auth-library";var Xr="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function Qr(){try{return await new Wr().getProjectId()||void 0}catch{return}}async function sf(n={}){let{enableTracing:e=!1,enableMetrics:t=!1}=n,o=await Qr();return o?{spanProcessors:e?[new Hr(new Kr({projectId:o}))]:[],metricReaders:t?[new Zr({exporter:new Vr({projectId:o}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(g.warn(Xr),{})}function af(){return Yr({detectors:[Jr]})}import{metrics as ei,trace as ti}from"@opentelemetry/api";import{logs as ni}from"@opentelemetry/api-logs";import{OTLPLogExporter as oi}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as ri}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as ii}from"@opentelemetry/exporter-trace-otlp-http";import{detectResources as si}from"@opentelemetry/resources";import{BatchLogRecordProcessor as ai,LoggerProvider as ci}from"@opentelemetry/sdk-logs";import{MeterProvider as li,PeriodicExportingMetricReader as ui}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as fi}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as di}from"@opentelemetry/sdk-trace-node";function Tf(n=[],e){let t=e||pi(),o=[...n,gi()],r=o.flatMap(a=>a.spanProcessors||[]),i=o.flatMap(a=>a.metricReaders||[]),s=o.flatMap(a=>a.logRecordProcessors||[]);if(r.length>0){let a=new di({resource:t,spanProcessors:r});a.register(),ti.setGlobalTracerProvider(a)}if(i.length>0){let a=new li({readers:i,resource:t});ei.setGlobalMeterProvider(a)}if(s.length>0){let a=new ci({resource:t,processors:s});ni.setGlobalLoggerProvider(a)}}function pi(){return si({detectors:[]})}function mi(){return{enableTracing:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT),enableMetrics:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT),enableLogging:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)}}function gi(n=mi()){let{enableTracing:e,enableMetrics:t,enableLogging:o}=n;return{spanProcessors:e?[new fi(new ii)]:[],metricReaders:t?[new ui({exporter:new ri})]:[],logRecordProcessors:o?[new ai(new oi)]:[]}}import{Client as hi}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Ci}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as vi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var Be=class{constructor(e){this.connectionParams=e}async createSession(){var t;let e=new hi({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new Ci(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":{let o=(t=this.connectionParams.transportOptions)!=null?t:{};!o.requestInit&&this.connectionParams.header!==void 0&&(o.requestInit={headers:this.connectionParams.header}),await e.connect(new vi(new URL(this.connectionParams.url),o));break}default:{let o=this.connectionParams;break}}return e}};import{Type as _}from"@google/genai";import{z as ne}from"zod";var Mf=ne.object({type:ne.literal("object"),properties:ne.record(ne.string(),ne.unknown()).optional(),required:ne.string().array().optional()});function xi(n){if(!n)return _.TYPE_UNSPECIFIED;switch(n.toLowerCase()){case"text":case"string":return _.STRING;case"number":return _.NUMBER;case"boolean":return _.BOOLEAN;case"integer":return _.INTEGER;case"array":return _.ARRAY;case"object":return _.OBJECT;default:return _.TYPE_UNSPECIFIED}}function qt(n){if(!n)return;function e(t){if(!t.type&&t.anyOf&&Array.isArray(t.anyOf)){let i=t.anyOf.find(s=>{let a=s.type;return a!=="null"&&a!=="NULL"});i&&(t=i)}t.type||(t.properties||t.$ref?t.type="object":t.items&&(t.type="array"));let o=xi(t.type),r={type:o,description:t.description};if(o===_.OBJECT){if(r.properties={},t.properties)for(let i in t.properties)r.properties[i]=e(t.properties[i]);r.required=t.required}else o===_.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(n)}var Ne=class extends b{constructor(e,t){super({name:e.name,description:e.description||""}),this.mcpTool=e,this.mcpSessionManager=t}_getDeclaration(){return{name:this.mcpTool.name,description:this.mcpTool.description,parameters:qt(this.mcpTool.inputSchema),response:qt(this.mcpTool.outputSchema)}}async runAsync(e){let t=await this.mcpSessionManager.createSession(),o={};return o.params={name:this.mcpTool.name,arguments:e.args},await t.callTool(o.params)}};var uo=class extends he{constructor(e,t=[]){super(t),this.mcpSessionManager=new Be(e)}async getTools(){let t=await(await this.mcpSessionManager.createSession()).listTools();g.debug(`number of tools: ${t.tools.length}`);for(let o of t.tools)g.debug(`tool: ${o.name}`);return t.tools.map(o=>new Ne(o,this.mcpSessionManager))}async close(){}};export{Fe as ActiveStreamingTool,Gt as AgentTool,eo as AuthCredentialTypes,w as BaseAgent,ce as BaseCodeExecutor,Ot as BaseExampleProvider,Q as BaseLlm,L as BaseLlmRequestProcessor,ze as BaseLlmResponseProcessor,K as BasePlugin,ke as BaseSessionService,b as BaseTool,he as BaseToolset,ue as BuiltInCodeExecutor,R as CallbackContext,B as FunctionTool,jr as GOOGLE_SEARCH,jt as GcsArtifactService,ee as Gemini,be as GoogleLLMVariant,Me as GoogleSearchTool,me as InMemoryArtifactService,V as InMemoryMemoryService,Pe as InMemoryPolicyEngine,Ft as InMemoryRunner,J as InMemorySessionService,M as InvocationContext,te as LLMRegistry,He as LiveRequestQueue,j as LlmAgent,ln as LogLevel,Mt as LoggingPlugin,$t as LongRunningFunctionTool,Rt as LoopAgent,Be as MCPSessionManager,Ne as MCPTool,uo as MCPToolset,wt as ParallelAgent,ge as PluginManager,io as PolicyOutcome,ro as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,T as ReadonlyContext,Y as Runner,Nt as SecurityPlugin,Lt as SequentialAgent,C as State,gt as StreamingMode,G as ToolConfirmation,F as ToolContext,v as createEvent,P as createEventActions,Le as createSession,_o as functionsExportedForTestingOnly,Dr as getAskUserConfirmationFunctionCalls,E as getFunctionCalls,S as getFunctionResponses,sf as getGcpExporters,af as getGcpResource,ko as getLogger,Jt as hasTrailingCodeExecutionResult,zr as isAgentTool,yo as isBaseAgent,Br as isBaseExampleProvider,it as isBaseLlm,Zo as isBaseTool,Z as isFinalResponse,rr as isFunctionTool,le as isGemini2OrAbove,A as isLlmAgent,Pr as isLoopAgent,kr as isParallelAgent,Or as isSequentialAgent,Tf as maybeSetOtelProviders,So as setLogLevel,Po as setLogger,go as stringifyContent,oe as version,ft as zodObjectToSchema};
|
|
88
1
|
/**
|
|
89
2
|
* @license
|
|
90
3
|
* Copyright 2025 Google LLC
|
|
91
4
|
* SPDX-License-Identifier: Apache-2.0
|
|
92
5
|
*/
|
|
93
|
-
|
|
6
|
+
import { FileArtifactService } from "./artifacts/file_artifact_service.js";
|
|
7
|
+
import { GcsArtifactService } from "./artifacts/gcs_artifact_service.js";
|
|
8
|
+
import { getArtifactServiceFromUri } from "./artifacts/registry.js";
|
|
9
|
+
export * from "./common.js";
|
|
10
|
+
import { DatabaseSessionService } from "./sessions/database_session_service.js";
|
|
11
|
+
import { getSessionServiceFromUri } from "./sessions/registry.js";
|
|
12
|
+
export * from "./telemetry/google_cloud.js";
|
|
13
|
+
export * from "./telemetry/setup.js";
|
|
14
|
+
export * from "./tools/mcp/mcp_session_manager.js";
|
|
15
|
+
export * from "./tools/mcp/mcp_tool.js";
|
|
16
|
+
export * from "./tools/mcp/mcp_toolset.js";
|
|
17
|
+
export {
|
|
18
|
+
DatabaseSessionService,
|
|
19
|
+
FileArtifactService,
|
|
20
|
+
GcsArtifactService,
|
|
21
|
+
getArtifactServiceFromUri,
|
|
22
|
+
getSessionServiceFromUri
|
|
23
|
+
};
|