@google/adk 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/cjs/agents/content_processor_utils.js +20 -8
  2. package/dist/cjs/agents/functions.js +23 -32
  3. package/dist/cjs/agents/llm_agent.js +1 -0
  4. package/dist/cjs/artifacts/gcs_artifact_service.js +140 -0
  5. package/dist/cjs/common.js +12 -0
  6. package/dist/cjs/index.js +5 -5
  7. package/dist/cjs/index.js.map +4 -4
  8. package/dist/cjs/models/base_llm.js +12 -3
  9. package/dist/cjs/models/google_llm.js +6 -20
  10. package/dist/cjs/models/registry.js +1 -1
  11. package/dist/cjs/telemetry/google_cloud.js +85 -0
  12. package/dist/cjs/telemetry/setup.js +97 -0
  13. package/dist/cjs/telemetry/tracing.js +231 -0
  14. package/dist/cjs/utils/client_labels.js +56 -0
  15. package/dist/cjs/version.js +1 -1
  16. package/dist/esm/agents/content_processor_utils.js +20 -8
  17. package/dist/esm/agents/functions.js +23 -32
  18. package/dist/esm/agents/llm_agent.js +1 -0
  19. package/dist/esm/artifacts/gcs_artifact_service.js +110 -0
  20. package/dist/esm/common.js +8 -0
  21. package/dist/esm/index.js +5 -5
  22. package/dist/esm/index.js.map +4 -4
  23. package/dist/esm/models/base_llm.js +12 -3
  24. package/dist/esm/models/google_llm.js +6 -20
  25. package/dist/esm/models/registry.js +1 -1
  26. package/dist/esm/telemetry/google_cloud.js +54 -0
  27. package/dist/esm/telemetry/setup.js +67 -0
  28. package/dist/esm/telemetry/tracing.js +195 -0
  29. package/dist/esm/utils/client_labels.js +26 -0
  30. package/dist/esm/version.js +1 -1
  31. package/dist/types/artifacts/gcs_artifact_service.d.ts +16 -0
  32. package/dist/types/common.d.ts +4 -0
  33. package/dist/types/index.d.ts +3 -0
  34. package/dist/types/models/base_llm.d.ts +6 -3
  35. package/dist/types/models/google_llm.d.ts +1 -2
  36. package/dist/types/models/registry.d.ts +6 -2
  37. package/dist/types/telemetry/google_cloud.d.ts +9 -0
  38. package/dist/types/telemetry/setup.d.ts +48 -0
  39. package/dist/types/telemetry/tracing.d.ts +111 -0
  40. package/dist/types/utils/client_labels.d.ts +9 -0
  41. package/dist/types/version.d.ts +1 -1
  42. package/dist/web/agents/content_processor_utils.js +20 -8
  43. package/dist/web/agents/functions.js +23 -32
  44. package/dist/web/agents/llm_agent.js +1 -0
  45. package/dist/web/artifacts/gcs_artifact_service.js +126 -0
  46. package/dist/web/common.js +8 -0
  47. package/dist/web/index.js +1 -1
  48. package/dist/web/index.js.map +4 -4
  49. package/dist/web/models/base_llm.js +12 -3
  50. package/dist/web/models/google_llm.js +6 -20
  51. package/dist/web/models/registry.js +1 -1
  52. package/dist/web/telemetry/google_cloud.js +54 -0
  53. package/dist/web/telemetry/setup.js +67 -0
  54. package/dist/web/telemetry/tracing.js +210 -0
  55. package/dist/web/utils/client_labels.js +26 -0
  56. package/dist/web/version.js +1 -1
  57. package/package.json +20 -4
@@ -0,0 +1,111 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ /**
7
+ * NOTE:
8
+ *
9
+ * We expect that the underlying GenAI SDK will provide a certain
10
+ * level of tracing and logging telemetry aligned with Open Telemetry
11
+ * Semantic Conventions (such as logging prompts, responses,
12
+ * request properties, etc.) and so the information that is recorded by the
13
+ * Agent Development Kit should be focused on the higher-level
14
+ * constructs of the framework that are not observable by the SDK.
15
+ */
16
+ import { Content } from '@google/genai';
17
+ import { Context } from '@opentelemetry/api';
18
+ import { BaseAgent } from '../agents/base_agent.js';
19
+ import { InvocationContext } from '../agents/invocation_context.js';
20
+ import { Event } from '../events/event.js';
21
+ import { LlmRequest } from '../models/llm_request.js';
22
+ import { LlmResponse } from '../models/llm_response.js';
23
+ import { BaseTool } from '../tools/base_tool.js';
24
+ export declare const tracer: import("@opentelemetry/api").Tracer;
25
+ export interface TraceAgentInvocationParams {
26
+ agent: BaseAgent;
27
+ invocationContext: InvocationContext;
28
+ }
29
+ /**
30
+ * Sets span attributes immediately available on agent invocation according to OTEL semconv version 1.37.
31
+ *
32
+ * @param params The parameters object containing agent and invocation context.
33
+ *
34
+ * Inference related fields are not set, due to their planned removal from invoke_agent span:
35
+ * https://github.com/open-telemetry/semantic-conventions/issues/2632
36
+ *
37
+ * `gen_ai.agent.id` is not set because currently it's unclear what attributes this field should have, specifically:
38
+ * - In which scope should it be unique (globally, given project, given agentic flow, given deployment).
39
+ * - Should it be unchanging between deployments, and how this should this be achieved.
40
+ *
41
+ * `gen_ai.data_source.id` is not set because it's not available.
42
+ * Closest type which could contain this information is types.GroundingMetadata, which does not have an ID.
43
+ *
44
+ * `server.*` attributes are not set pending confirmation from aabmass.
45
+ */
46
+ export declare function traceAgentInvocation({ agent, invocationContext, }: TraceAgentInvocationParams): void;
47
+ export interface TraceToolCallParams {
48
+ tool: BaseTool;
49
+ args: Record<string, unknown>;
50
+ functionResponseEvent: Event;
51
+ }
52
+ /**
53
+ * Traces tool call.
54
+ *
55
+ * @param params The parameters object containing tool, args, and function response event.
56
+ */
57
+ export declare function traceToolCall({ tool, args, functionResponseEvent, }: TraceToolCallParams): void;
58
+ export interface TraceMergedToolCallsParams {
59
+ responseEventId: string;
60
+ functionResponseEvent: Event;
61
+ }
62
+ /**
63
+ * Traces merged tool call events.
64
+ *
65
+ * Calling this function is not needed for telemetry purposes. This is provided
66
+ * for preventing /debug/trace requests (typically sent by web UI).
67
+ *
68
+ * @param params The parameters object containing response event ID and function response event.
69
+ */
70
+ export declare function traceMergedToolCalls({ responseEventId, functionResponseEvent, }: TraceMergedToolCallsParams): void;
71
+ export interface TraceCallLlmParams {
72
+ invocationContext: InvocationContext;
73
+ eventId: string;
74
+ llmRequest: LlmRequest;
75
+ llmResponse: LlmResponse;
76
+ }
77
+ /**
78
+ * Traces a call to the LLM.
79
+ *
80
+ * This function records details about the LLM request and response as
81
+ * attributes on the current OpenTelemetry span.
82
+ *
83
+ * @param params The parameters object containing invocationContext, eventId, llmRequest, and llmResponse.
84
+ */
85
+ export declare function traceCallLlm({ invocationContext, eventId, llmRequest, llmResponse, }: TraceCallLlmParams): void;
86
+ export interface TraceSendDataParams {
87
+ /** The invocation context for the current agent run. */
88
+ invocationContext: InvocationContext;
89
+ /** The ID of the event. */
90
+ eventId: string;
91
+ /** A list of content objects. */
92
+ data: Content[];
93
+ }
94
+ /**
95
+ * Traces the sending of data to the agent.
96
+ *
97
+ * This function records details about the data sent to the agent as
98
+ * attributes on the current OpenTelemetry span.
99
+ *
100
+ * @param params The parameters object containing invocationContext, eventId, and data.
101
+ */
102
+ export declare function traceSendData({ invocationContext, eventId, data, }: TraceSendDataParams): void;
103
+ /**
104
+ * Binds an async generator to OpenTelemetry context for trace propagation.
105
+ * This is a temporary solution.
106
+ * @param ctx - The OpenTelemetry context to bind the generator to
107
+ * @param generator - The async generator to be bound to the context
108
+ *
109
+ * @returns A new async generator that executes all operations within the provided context
110
+ */
111
+ export declare function bindAsyncGenerator<T = unknown, TReturn = any, TNext = unknown>(ctx: Context, generator: AsyncGenerator<T, TReturn, TNext>): AsyncGenerator<T, TReturn, TNext>;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ /**
7
+ * Returns the current list of client labels that can be added to HTTP Headers.
8
+ */
9
+ export declare function getClientLabels(): string[];
@@ -3,4 +3,4 @@
3
3
  * Copyright 2025 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- export declare const version = "0.1.0";
6
+ export declare const version = "0.2.0";
@@ -73,8 +73,8 @@ function isEventFromAnotherAgent(agentName, event) {
73
73
  return !!agentName && event.author !== agentName && event.author !== "user";
74
74
  }
75
75
  function convertForeignEvent(event) {
76
- var _a, _b, _c, _d, _e;
77
- if (!((_a = event.content) == null ? void 0 : _a.parts)) {
76
+ var _a, _b, _c, _d, _e, _f;
77
+ if (!((_b = (_a = event.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.length)) {
78
78
  return event;
79
79
  }
80
80
  const content = {
@@ -85,19 +85,21 @@ function convertForeignEvent(event) {
85
85
  };
86
86
  for (const part of event.content.parts) {
87
87
  if (part.text && !part.thought) {
88
- (_b = content.parts) == null ? void 0 : _b.push({
88
+ (_c = content.parts) == null ? void 0 : _c.push({
89
89
  text: "[".concat(event.author, "] said: ").concat(part.text)
90
90
  });
91
91
  } else if (part.functionCall) {
92
- (_c = content.parts) == null ? void 0 : _c.push({
93
- text: "[".concat(event.author, "] called tool `").concat(part.functionCall.name, "` with parameters: ").concat(part.functionCall.args)
92
+ const argsText = safeStringify(part.functionCall.args);
93
+ (_d = content.parts) == null ? void 0 : _d.push({
94
+ text: "[".concat(event.author, "] called tool `").concat(part.functionCall.name, "` with parameters: ").concat(argsText)
94
95
  });
95
96
  } else if (part.functionResponse) {
96
- (_d = content.parts) == null ? void 0 : _d.push({
97
- text: "[".concat(event.author, "] tool `").concat(part.functionResponse.name, "` returned result: ").concat(part.functionResponse.response)
97
+ const responseText = safeStringify(part.functionResponse.response);
98
+ (_e = content.parts) == null ? void 0 : _e.push({
99
+ text: "[".concat(event.author, "] tool `").concat(part.functionResponse.name, "` returned result: ").concat(responseText)
98
100
  });
99
101
  } else {
100
- (_e = content.parts) == null ? void 0 : _e.push(part);
102
+ (_f = content.parts) == null ? void 0 : _f.push(part);
101
103
  }
102
104
  }
103
105
  return createEvent({
@@ -262,6 +264,16 @@ function rearrangeEventsForAsyncFunctionResponsesInHistory(events) {
262
264
  }
263
265
  return resultEvents;
264
266
  }
267
+ function safeStringify(obj) {
268
+ if (typeof obj === "string") {
269
+ return obj;
270
+ }
271
+ try {
272
+ return JSON.stringify(obj);
273
+ } catch (e) {
274
+ return String(obj);
275
+ }
276
+ }
265
277
  export {
266
278
  getContents,
267
279
  getCurrentTurnContents
@@ -3,6 +3,7 @@
3
3
  * Copyright 2025 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
+ import { createUserContent } from "@google/genai";
6
7
  import { createEvent, getFunctionCalls } from "../events/event.js";
7
8
  import { mergeEventActions } from "../events/event_actions.js";
8
9
  import { ToolContext } from "../tools/tool_context.js";
@@ -126,30 +127,6 @@ async function callToolAsync(tool, args, toolContext) {
126
127
  logger.debug("callToolAsync ".concat(tool.name));
127
128
  return await tool.runAsync({ args, toolContext });
128
129
  }
129
- function buildResponseEvent(tool, functionResult, toolContext, invocationContext) {
130
- let responseResult = functionResult;
131
- if (typeof functionResult !== "object" || functionResult == null) {
132
- responseResult = { result: functionResult };
133
- }
134
- const partFunctionResponse = {
135
- functionResponse: {
136
- name: tool.name,
137
- response: responseResult,
138
- id: toolContext.functionCallId
139
- }
140
- };
141
- const content = {
142
- role: "user",
143
- parts: [partFunctionResponse]
144
- };
145
- return createEvent({
146
- invocationId: invocationContext.invocationId,
147
- author: invocationContext.agent.name,
148
- content,
149
- actions: toolContext.actions,
150
- branch: invocationContext.branch
151
- });
152
- }
153
130
  async function handleFunctionCallsAsync({
154
131
  invocationContext,
155
132
  functionCallEvent,
@@ -200,6 +177,7 @@ async function handleFunctionCallList({
200
177
  logger.debug("execute_tool ".concat(tool.name));
201
178
  const functionArgs = (_a = functionCall.args) != null ? _a : {};
202
179
  let functionResponse = null;
180
+ let functionResponseError;
203
181
  functionResponse = await invocationContext.pluginManager.runBeforeToolCallback({
204
182
  tool,
205
183
  toolArgs: functionArgs,
@@ -236,10 +214,11 @@ async function handleFunctionCallList({
236
214
  );
237
215
  if (onToolErrorResponse) {
238
216
  functionResponse = onToolErrorResponse;
217
+ } else {
218
+ functionResponseError = e.message;
239
219
  }
240
220
  } else {
241
- logger.error("Unknown error on tool execution type", e);
242
- throw e;
221
+ functionResponseError = e;
243
222
  }
244
223
  }
245
224
  }
@@ -268,12 +247,24 @@ async function handleFunctionCallList({
268
247
  if (tool.isLongRunning && !functionResponse) {
269
248
  continue;
270
249
  }
271
- const functionResponseEvent = buildResponseEvent(
272
- tool,
273
- functionResponse,
274
- toolContext,
275
- invocationContext
276
- );
250
+ if (functionResponseError) {
251
+ functionResponse = { error: functionResponseError };
252
+ } else if (typeof functionResponse !== "object" || functionResponse == null) {
253
+ functionResponse = { result: functionResponse };
254
+ }
255
+ const functionResponseEvent = createEvent({
256
+ invocationId: invocationContext.invocationId,
257
+ author: invocationContext.agent.name,
258
+ content: createUserContent({
259
+ functionResponse: {
260
+ id: toolContext.functionCallId,
261
+ name: tool.name,
262
+ response: functionResponse
263
+ }
264
+ }),
265
+ actions: toolContext.actions,
266
+ branch: invocationContext.branch
267
+ });
277
268
  logger.debug("traceToolCall", {
278
269
  tool: tool.name,
279
270
  args: functionArgs,
@@ -181,6 +181,7 @@ class AgentTransferLlmRequestProcessor extends BaseLlmRequestProcessor {
181
181
  throw new Error("toolContext is required.");
182
182
  }
183
183
  toolContext.actions.transferToAgent = args.agentName;
184
+ return "Transfer queued";
184
185
  }
185
186
  });
186
187
  }
@@ -0,0 +1,126 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ /**
21
+ * @license
22
+ * Copyright 2025 Google LLC
23
+ * SPDX-License-Identifier: Apache-2.0
24
+ */
25
+ import { Storage } from "@google-cloud/storage";
26
+ import { createPartFromBase64, createPartFromText } from "@google/genai";
27
+ class GcsArtifactService {
28
+ constructor(bucket) {
29
+ this.bucket = new Storage().bucket(bucket);
30
+ }
31
+ async saveArtifact(request) {
32
+ const versions = await this.listVersions(request);
33
+ const version = versions.length > 0 ? Math.max(...versions) + 1 : 0;
34
+ const file = this.bucket.file(getFileName(__spreadProps(__spreadValues({}, request), {
35
+ version
36
+ })));
37
+ if (request.artifact.inlineData) {
38
+ await file.save(JSON.stringify(request.artifact.inlineData.data), {
39
+ contentType: request.artifact.inlineData.mimeType
40
+ });
41
+ return version;
42
+ }
43
+ if (request.artifact.text) {
44
+ await file.save(request.artifact.text, {
45
+ contentType: "text/plain"
46
+ });
47
+ return version;
48
+ }
49
+ throw new Error("Artifact must have either inlineData or text.");
50
+ }
51
+ async loadArtifact(request) {
52
+ let version = request.version;
53
+ if (version === void 0) {
54
+ const versions = await this.listVersions(request);
55
+ if (versions.length === 0) {
56
+ return void 0;
57
+ }
58
+ version = Math.max(...versions);
59
+ }
60
+ const file = this.bucket.file(getFileName(__spreadProps(__spreadValues({}, request), {
61
+ version
62
+ })));
63
+ const [[metadata], [rawDataBuffer]] = await Promise.all([file.getMetadata(), file.download()]);
64
+ if (metadata.contentType === "text/plain") {
65
+ return createPartFromText(rawDataBuffer.toString("utf-8"));
66
+ }
67
+ return createPartFromBase64(
68
+ rawDataBuffer.toString("base64"),
69
+ metadata.contentType
70
+ );
71
+ }
72
+ async listArtifactKeys(request) {
73
+ const fileNames = [];
74
+ const sessionPrefix = "".concat(request.appName, "/").concat(request.userId, "/").concat(request.sessionId, "/");
75
+ const usernamePrefix = "".concat(request.appName, "/").concat(request.userId, "/user/");
76
+ const [
77
+ [sessionFiles],
78
+ [userSessionFiles]
79
+ ] = await Promise.all([
80
+ this.bucket.getFiles({ prefix: sessionPrefix }),
81
+ this.bucket.getFiles({ prefix: usernamePrefix })
82
+ ]);
83
+ for (const file of sessionFiles) {
84
+ fileNames.push(file.name.split("/").pop());
85
+ }
86
+ for (const file of userSessionFiles) {
87
+ fileNames.push(file.name.split("/").pop());
88
+ }
89
+ return fileNames.sort((a, b) => a.localeCompare(b));
90
+ }
91
+ async deleteArtifact(request) {
92
+ const versions = await this.listVersions(request);
93
+ await Promise.all(versions.map((version) => {
94
+ const file = this.bucket.file(getFileName(__spreadProps(__spreadValues({}, request), {
95
+ version
96
+ })));
97
+ return file.delete();
98
+ }));
99
+ return;
100
+ }
101
+ async listVersions(request) {
102
+ const prefix = getFileName(request);
103
+ const [files] = await this.bucket.getFiles({ prefix });
104
+ const versions = [];
105
+ for (const file of files) {
106
+ const version = file.name.split("/").pop();
107
+ versions.push(parseInt(version, 10));
108
+ }
109
+ return versions;
110
+ }
111
+ }
112
+ function getFileName({
113
+ appName,
114
+ userId,
115
+ sessionId,
116
+ filename,
117
+ version
118
+ }) {
119
+ if (filename.startsWith("user:")) {
120
+ return "".concat(appName, "/").concat(userId, "/user/").concat(filename, "/").concat(version);
121
+ }
122
+ return "".concat(appName, "/").concat(userId, "/").concat(sessionId, "/").concat(filename, "/").concat(version);
123
+ }
124
+ export {
125
+ GcsArtifactService
126
+ };
@@ -15,9 +15,11 @@ import { StreamingMode } from "./agents/run_config.js";
15
15
  import { SequentialAgent } from "./agents/sequential_agent.js";
16
16
  import { InMemoryArtifactService } from "./artifacts/in_memory_artifact_service.js";
17
17
  import { createEvent, getFunctionCalls, getFunctionResponses, hasTrailingCodeExecutionResult, isFinalResponse, stringifyContent } from "./events/event.js";
18
+ import { createEventActions } from "./events/event_actions.js";
18
19
  import { InMemoryMemoryService } from "./memory/in_memory_memory_service.js";
19
20
  import { BaseLlm } from "./models/base_llm.js";
20
21
  import { Gemini } from "./models/google_llm.js";
22
+ import { LLMRegistry } from "./models/registry.js";
21
23
  import { BasePlugin } from "./plugins/base_plugin.js";
22
24
  import { LoggingPlugin } from "./plugins/logging_plugin.js";
23
25
  import { PluginManager } from "./plugins/plugin_manager.js";
@@ -26,6 +28,7 @@ import { InMemoryRunner } from "./runner/in_memory_runner.js";
26
28
  import { Runner } from "./runner/runner.js";
27
29
  import { InMemorySessionService } from "./sessions/in_memory_session_service.js";
28
30
  import { createSession } from "./sessions/session.js";
31
+ import { State } from "./sessions/state.js";
29
32
  import { AgentTool } from "./tools/agent_tool.js";
30
33
  import { BaseTool } from "./tools/base_tool.js";
31
34
  import { BaseToolset } from "./tools/base_toolset.js";
@@ -36,6 +39,7 @@ import { ToolConfirmation } from "./tools/tool_confirmation.js";
36
39
  import { ToolContext } from "./tools/tool_context.js";
37
40
  import { LogLevel, setLogLevel } from "./utils/logger.js";
38
41
  import { zodObjectToSchema } from "./utils/simple_zod_to_json.js";
42
+ import { version } from "./version.js";
39
43
  export * from "./artifacts/base_artifact_service.js";
40
44
  export * from "./memory/base_memory_service.js";
41
45
  export * from "./sessions/base_session_service.js";
@@ -57,6 +61,7 @@ export {
57
61
  InMemoryRunner,
58
62
  InMemorySessionService,
59
63
  InvocationContext,
64
+ LLMRegistry,
60
65
  LiveRequestQueue,
61
66
  LlmAgent,
62
67
  LogLevel,
@@ -70,10 +75,12 @@ export {
70
75
  Runner,
71
76
  SecurityPlugin,
72
77
  SequentialAgent,
78
+ State,
73
79
  StreamingMode,
74
80
  ToolConfirmation,
75
81
  ToolContext,
76
82
  createEvent,
83
+ createEventActions,
77
84
  createSession,
78
85
  functionsExportedForTestingOnly,
79
86
  getAskUserConfirmationFunctionCalls,
@@ -83,5 +90,6 @@ export {
83
90
  isFinalResponse,
84
91
  setLogLevel,
85
92
  stringifyContent,
93
+ version,
86
94
  zodObjectToSchema
87
95
  };