google-adk 1.0.0__py3-none-any.whl → 1.1.1__py3-none-any.whl

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 (94) hide show
  1. google/adk/agents/callback_context.py +2 -1
  2. google/adk/agents/readonly_context.py +3 -1
  3. google/adk/auth/auth_credential.py +4 -1
  4. google/adk/cli/browser/index.html +4 -4
  5. google/adk/cli/browser/{main-QOEMUXM4.js → main-PKDNKWJE.js} +59 -59
  6. google/adk/cli/browser/polyfills-B6TNHZQ6.js +17 -0
  7. google/adk/cli/cli.py +3 -2
  8. google/adk/cli/cli_eval.py +6 -85
  9. google/adk/cli/cli_tools_click.py +39 -10
  10. google/adk/cli/fast_api.py +53 -184
  11. google/adk/cli/utils/agent_loader.py +137 -0
  12. google/adk/cli/utils/cleanup.py +40 -0
  13. google/adk/cli/utils/evals.py +2 -1
  14. google/adk/cli/utils/logs.py +2 -7
  15. google/adk/code_executors/code_execution_utils.py +2 -1
  16. google/adk/code_executors/container_code_executor.py +0 -1
  17. google/adk/code_executors/vertex_ai_code_executor.py +6 -8
  18. google/adk/evaluation/eval_case.py +3 -1
  19. google/adk/evaluation/eval_metrics.py +74 -0
  20. google/adk/evaluation/eval_result.py +86 -0
  21. google/adk/evaluation/eval_set.py +2 -0
  22. google/adk/evaluation/eval_set_results_manager.py +47 -0
  23. google/adk/evaluation/eval_sets_manager.py +2 -1
  24. google/adk/evaluation/evaluator.py +2 -0
  25. google/adk/evaluation/local_eval_set_results_manager.py +113 -0
  26. google/adk/evaluation/local_eval_sets_manager.py +4 -4
  27. google/adk/evaluation/response_evaluator.py +2 -1
  28. google/adk/evaluation/trajectory_evaluator.py +3 -2
  29. google/adk/examples/base_example_provider.py +1 -0
  30. google/adk/flows/llm_flows/base_llm_flow.py +4 -6
  31. google/adk/flows/llm_flows/contents.py +3 -1
  32. google/adk/flows/llm_flows/instructions.py +7 -77
  33. google/adk/flows/llm_flows/single_flow.py +1 -1
  34. google/adk/models/base_llm.py +2 -1
  35. google/adk/models/base_llm_connection.py +2 -0
  36. google/adk/models/google_llm.py +4 -1
  37. google/adk/models/lite_llm.py +3 -2
  38. google/adk/models/llm_response.py +2 -1
  39. google/adk/runners.py +36 -4
  40. google/adk/sessions/_session_util.py +2 -1
  41. google/adk/sessions/database_session_service.py +5 -8
  42. google/adk/sessions/vertex_ai_session_service.py +28 -13
  43. google/adk/telemetry.py +4 -2
  44. google/adk/tools/agent_tool.py +1 -1
  45. google/adk/tools/apihub_tool/apihub_toolset.py +1 -1
  46. google/adk/tools/apihub_tool/clients/apihub_client.py +10 -3
  47. google/adk/tools/apihub_tool/clients/secret_client.py +1 -0
  48. google/adk/tools/application_integration_tool/application_integration_toolset.py +6 -2
  49. google/adk/tools/application_integration_tool/clients/connections_client.py +8 -1
  50. google/adk/tools/application_integration_tool/clients/integration_client.py +3 -1
  51. google/adk/tools/application_integration_tool/integration_connector_tool.py +1 -1
  52. google/adk/tools/base_toolset.py +40 -2
  53. google/adk/tools/bigquery/__init__.py +38 -0
  54. google/adk/tools/bigquery/bigquery_credentials.py +217 -0
  55. google/adk/tools/bigquery/bigquery_tool.py +116 -0
  56. google/adk/tools/bigquery/bigquery_toolset.py +86 -0
  57. google/adk/tools/bigquery/client.py +33 -0
  58. google/adk/tools/bigquery/metadata_tool.py +249 -0
  59. google/adk/tools/bigquery/query_tool.py +76 -0
  60. google/adk/tools/function_parameter_parse_util.py +7 -0
  61. google/adk/tools/function_tool.py +33 -3
  62. google/adk/tools/get_user_choice_tool.py +1 -0
  63. google/adk/tools/google_api_tool/__init__.py +17 -11
  64. google/adk/tools/google_api_tool/google_api_tool.py +1 -1
  65. google/adk/tools/google_api_tool/google_api_toolset.py +0 -14
  66. google/adk/tools/google_api_tool/google_api_toolsets.py +8 -2
  67. google/adk/tools/google_search_tool.py +2 -2
  68. google/adk/tools/mcp_tool/conversion_utils.py +6 -2
  69. google/adk/tools/mcp_tool/mcp_session_manager.py +62 -188
  70. google/adk/tools/mcp_tool/mcp_tool.py +27 -24
  71. google/adk/tools/mcp_tool/mcp_toolset.py +76 -131
  72. google/adk/tools/openapi_tool/auth/credential_exchangers/base_credential_exchanger.py +1 -3
  73. google/adk/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.py +6 -7
  74. google/adk/tools/openapi_tool/common/common.py +5 -1
  75. google/adk/tools/openapi_tool/openapi_spec_parser/__init__.py +7 -2
  76. google/adk/tools/openapi_tool/openapi_spec_parser/openapi_toolset.py +2 -7
  77. google/adk/tools/openapi_tool/openapi_spec_parser/operation_parser.py +5 -1
  78. google/adk/tools/openapi_tool/openapi_spec_parser/rest_api_tool.py +11 -1
  79. google/adk/tools/toolbox_toolset.py +31 -3
  80. google/adk/utils/__init__.py +13 -0
  81. google/adk/utils/instructions_utils.py +131 -0
  82. google/adk/version.py +1 -1
  83. {google_adk-1.0.0.dist-info → google_adk-1.1.1.dist-info}/METADATA +12 -15
  84. {google_adk-1.0.0.dist-info → google_adk-1.1.1.dist-info}/RECORD +87 -78
  85. google/adk/agents/base_agent.py.orig +0 -330
  86. google/adk/cli/browser/polyfills-FFHMD2TL.js +0 -18
  87. google/adk/cli/fast_api.py.orig +0 -822
  88. google/adk/memory/base_memory_service.py.orig +0 -76
  89. google/adk/models/google_llm.py.orig +0 -305
  90. google/adk/tools/_built_in_code_execution_tool.py +0 -70
  91. google/adk/tools/mcp_tool/mcp_session_manager.py.orig +0 -322
  92. {google_adk-1.0.0.dist-info → google_adk-1.1.1.dist-info}/WHEEL +0 -0
  93. {google_adk-1.0.0.dist-info → google_adk-1.1.1.dist-info}/entry_points.txt +0 -0
  94. {google_adk-1.0.0.dist-info → google_adk-1.1.1.dist-info}/licenses/LICENSE +0 -0
@@ -1,322 +0,0 @@
1
- # Copyright 2025 Google LLC
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- import asyncio
16
- from contextlib import AsyncExitStack, asynccontextmanager
17
- import functools
18
- import logging
19
- import sys
20
- from typing import Any, Optional, TextIO
21
- import anyio
22
- from pydantic import BaseModel
23
-
24
- try:
25
- from mcp import ClientSession, StdioServerParameters
26
- from mcp.client.sse import sse_client
27
- from mcp.client.stdio import stdio_client
28
- except ImportError as e:
29
- import sys
30
-
31
- if sys.version_info < (3, 10):
32
- raise ImportError(
33
- 'MCP Tool requires Python 3.10 or above. Please upgrade your Python'
34
- ' version.'
35
- ) from e
36
- else:
37
- raise e
38
-
39
- logger = logging.getLogger(__name__)
40
-
41
-
42
- class SseServerParams(BaseModel):
43
- """Parameters for the MCP SSE connection.
44
-
45
- See MCP SSE Client documentation for more details.
46
- https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/client/sse.py
47
- """
48
-
49
- url: str
50
- headers: dict[str, Any] | None = None
51
- timeout: float = 5
52
- sse_read_timeout: float = 60 * 5
53
-
54
-
55
- def retry_on_closed_resource(async_reinit_func_name: str):
56
- """Decorator to automatically reinitialize session and retry action.
57
-
58
- When MCP session was closed, the decorator will automatically recreate the
59
- session and retry the action with the same parameters.
60
-
61
- Note:
62
- 1. async_reinit_func_name is the name of the class member function that
63
- reinitializes the MCP session.
64
- 2. Both the decorated function and the async_reinit_func_name must be async
65
- functions.
66
-
67
- Usage:
68
- class MCPTool:
69
- ...
70
- async def create_session(self):
71
- self.session = ...
72
-
73
- @retry_on_closed_resource('create_session')
74
- async def use_session(self):
75
- await self.session.call_tool()
76
-
77
- Args:
78
- async_reinit_func_name: The name of the async function to recreate session.
79
-
80
- Returns:
81
- The decorated function.
82
- """
83
-
84
- def decorator(func):
85
- @functools.wraps(
86
- func
87
- ) # Preserves original function metadata (name, docstring)
88
- async def wrapper(self, *args, **kwargs):
89
- try:
90
- return await func(self, *args, **kwargs)
91
- except anyio.ClosedResourceError:
92
- try:
93
- if hasattr(self, async_reinit_func_name) and callable(
94
- getattr(self, async_reinit_func_name)
95
- ):
96
- async_init_fn = getattr(self, async_reinit_func_name)
97
- await async_init_fn()
98
- else:
99
- raise ValueError(
100
- f'Function {async_reinit_func_name} does not exist in decorated'
101
- ' class. Please check the function name in'
102
- ' retry_on_closed_resource decorator.'
103
- )
104
- except Exception as reinit_err:
105
- raise RuntimeError(
106
- f'Error reinitializing: {reinit_err}'
107
- ) from reinit_err
108
- return await func(self, *args, **kwargs)
109
-
110
- return wrapper
111
-
112
- return decorator
113
-
114
-
115
- @asynccontextmanager
116
- async def tracked_stdio_client(server, errlog, process=None):
117
- """A wrapper around stdio_client that ensures proper process tracking and cleanup."""
118
- our_process = process
119
-
120
- # If no process was provided, create one
121
- if our_process is None:
122
- our_process = await asyncio.create_subprocess_exec(
123
- server.command,
124
- *server.args,
125
- stdin=asyncio.subprocess.PIPE,
126
- stdout=asyncio.subprocess.PIPE,
127
- stderr=errlog,
128
- )
129
-
130
- # Use the original stdio_client, but ensure process cleanup
131
- try:
132
- async with stdio_client(server=server, errlog=errlog) as client:
133
- yield client, our_process
134
- finally:
135
- # Ensure the process is properly terminated if it still exists
136
- if our_process and our_process.returncode is None:
137
- try:
138
- logger.info(
139
- f'Terminating process {our_process.pid} from tracked_stdio_client'
140
- )
141
- our_process.terminate()
142
- try:
143
- await asyncio.wait_for(our_process.wait(), timeout=3.0)
144
- except asyncio.TimeoutError:
145
- # Force kill if it doesn't terminate quickly
146
- if our_process.returncode is None:
147
- logger.warning(f'Forcing kill of process {our_process.pid}')
148
- our_process.kill()
149
- except ProcessLookupError:
150
- # Process already gone, that's fine
151
- logger.info(f'Process {our_process.pid} already terminated')
152
-
153
-
154
- class MCPSessionManager:
155
- """Manages MCP client sessions.
156
-
157
- This class provides methods for creating and initializing MCP client sessions,
158
- handling different connection parameters (Stdio and SSE).
159
- """
160
-
161
- def __init__(
162
- self,
163
- connection_params: StdioServerParameters | SseServerParams,
164
- exit_stack: AsyncExitStack,
165
- errlog: TextIO = sys.stderr,
166
- ) -> ClientSession:
167
- """Initializes the MCP session manager.
168
-
169
- Example usage:
170
- ```
171
- mcp_session_manager = MCPSessionManager(
172
- connection_params=connection_params,
173
- exit_stack=exit_stack,
174
- )
175
- session = await mcp_session_manager.create_session()
176
- ```
177
-
178
- Args:
179
- connection_params: Parameters for the MCP connection (Stdio or SSE).
180
- exit_stack: AsyncExitStack to manage the session lifecycle.
181
- errlog: (Optional) TextIO stream for error logging. Use only for
182
- initializing a local stdio MCP session.
183
- """
184
-
185
- self._connection_params = connection_params
186
- self._exit_stack = exit_stack
187
- self._errlog = errlog
188
- self._process = None # Track the subprocess
189
- self._active_processes = set() # Track all processes created
190
- self._active_file_handles = set() # Track file handles
191
-
192
- async def create_session(
193
- self,
194
- ) -> tuple[ClientSession, Optional[asyncio.subprocess.Process]]:
195
- """Creates a new MCP session and tracks the associated process."""
196
- session, process = await self._initialize_session(
197
- connection_params=self._connection_params,
198
- exit_stack=self._exit_stack,
199
- errlog=self._errlog,
200
- )
201
- self._process = process # Store reference to process
202
-
203
- # Track the process
204
- if process:
205
- self._active_processes.add(process)
206
-
207
- return session, process
208
-
209
- @classmethod
210
- async def _initialize_session(
211
- cls,
212
- *,
213
- connection_params: StdioServerParameters | SseServerParams,
214
- exit_stack: AsyncExitStack,
215
- errlog: TextIO = sys.stderr,
216
- ) -> tuple[ClientSession, Optional[asyncio.subprocess.Process]]:
217
- """Initializes an MCP client session.
218
-
219
- Args:
220
- connection_params: Parameters for the MCP connection (Stdio or SSE).
221
- exit_stack: AsyncExitStack to manage the session lifecycle.
222
- errlog: (Optional) TextIO stream for error logging. Use only for
223
- initializing a local stdio MCP session.
224
-
225
- Returns:
226
- ClientSession: The initialized MCP client session.
227
- """
228
- process = None
229
-
230
- if isinstance(connection_params, StdioServerParameters):
231
- # For stdio connections, we need to track the subprocess
232
- client, process = await cls._create_stdio_client(
233
- server=connection_params,
234
- errlog=errlog,
235
- exit_stack=exit_stack,
236
- )
237
- elif isinstance(connection_params, SseServerParams):
238
- # For SSE connections, create the client without a subprocess
239
- client = sse_client(
240
- url=connection_params.url,
241
- headers=connection_params.headers,
242
- timeout=connection_params.timeout,
243
- sse_read_timeout=connection_params.sse_read_timeout,
244
- )
245
- else:
246
- raise ValueError(
247
- 'Unable to initialize connection. Connection should be'
248
- ' StdioServerParameters or SseServerParams, but got'
249
- f' {connection_params}'
250
- )
251
-
252
- # Create the session with the client
253
- transports = await exit_stack.enter_async_context(client)
254
- session = await exit_stack.enter_async_context(ClientSession(*transports))
255
- await session.initialize()
256
-
257
- return session, process
258
-
259
- @staticmethod
260
- async def _create_stdio_client(
261
- server: StdioServerParameters,
262
- errlog: TextIO,
263
- exit_stack: AsyncExitStack,
264
- ) -> tuple[Any, asyncio.subprocess.Process]:
265
- """Create stdio client and return both the client and process.
266
-
267
- This implementation adapts to how the MCP stdio_client is created.
268
- The actual implementation may need to be adjusted based on the MCP library
269
- structure.
270
- """
271
- # Create the subprocess directly so we can track it
272
- process = await asyncio.create_subprocess_exec(
273
- server.command,
274
- *server.args,
275
- stdin=asyncio.subprocess.PIPE,
276
- stdout=asyncio.subprocess.PIPE,
277
- stderr=errlog,
278
- )
279
-
280
- # Create the stdio client using the MCP library
281
- try:
282
- # Method 1: Try using the existing process if stdio_client supports it
283
- client = stdio_client(server=server, errlog=errlog, process=process)
284
- except TypeError:
285
- # Method 2: If the above doesn't work, let stdio_client create its own process
286
- # and we'll need to terminate both processes later
287
- logger.warning(
288
- 'Using stdio_client with its own process - may lead to duplicate'
289
- ' processes'
290
- )
291
- client = stdio_client(server=server, errlog=errlog)
292
-
293
- return client, process
294
-
295
- async def _emergency_cleanup(self):
296
- """Perform emergency cleanup of resources when normal cleanup fails."""
297
- logger.info('Performing emergency cleanup of MCPSessionManager resources')
298
-
299
- # Clean up any tracked processes
300
- for proc in list(self._active_processes):
301
- try:
302
- if proc and proc.returncode is None:
303
- logger.info(f'Emergency termination of process {proc.pid}')
304
- proc.terminate()
305
- try:
306
- await asyncio.wait_for(proc.wait(), timeout=1.0)
307
- except asyncio.TimeoutError:
308
- logger.warning(f"Process {proc.pid} didn't terminate, forcing kill")
309
- proc.kill()
310
- self._active_processes.remove(proc)
311
- except Exception as e:
312
- logger.error(f'Error during process cleanup: {e}')
313
-
314
- # Clean up any tracked file handles
315
- for handle in list(self._active_file_handles):
316
- try:
317
- if not handle.closed:
318
- logger.info('Closing file handle')
319
- handle.close()
320
- self._active_file_handles.remove(handle)
321
- except Exception as e:
322
- logger.error(f'Error closing file handle: {e}')