Merge https://github.com/google/adk-python/pull/4221
### Link to Issue or Description of Change
N/A
**2. Or, if no issue exists, describe the change:**
Fixing various typos in .py files to improve quality: see commit diffs for details
**Problem:**
See above
**Solution:**
Fixing the typos
### Testing Plan
N/A
**Unit Tests:**
N/A
**Manual End-to-End (E2E) Tests:**
N/A
### Checklist
- [X] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [X] I have performed a self-review of my own code.
- [N/A] I have commented my code, particularly in hard-to-understand areas.
- [N/A ] I have added tests that prove my fix is effective or that my feature works.
- [N/A] New and existing unit tests pass locally with my changes.
- [N/A] I have manually tested my changes end-to-end.
- [N/A ] Any dependent changes have been merged and published in downstream modules.
### Additional context
N/A
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4221 from didier-durand:fix-typos-e 1bcc8e05cdc116451222dd7fd7b0657745f769c1
PiperOrigin-RevId: 859332402
Merge https://github.com/google/adk-python/pull/4136
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
Allow google search tool to set different model #4135
**2. Or, if no issue exists, describe the change:**
_If applicable, please follow the issue templates to provide as much detail as
possible._
**Problem:**
Currently, the Google Search tool inherits and uses the same LLM model set from the parent agent for processing and summarizing search results. This creates a limitation for users who wish to decouple the agent's reasoning model from the model used for search summarization (e.g., for cost optimization or using a lightweight model for simpler summarization tasks).
**Solution:**
I have updated the Google Search tool to accept an optional LLM model parameter.
Custom Model: Users can now explicitly specify which model should be used for processing search results.
Default Behavior: If no model is specified, the tool defaults to the parent agent's model, ensuring backward compatibility.
```
# If a custom model is specified, use it instead of the original model
if self.model is not None:
llm_request.model = self.model
```
### Testing Plan
Added a new test case test_process_llm_request_with_custom_model in [test_google_search_tool.py] that verifies:
When a custom model parameter is provided to GoogleSearchTool, it overrides the model from the incoming llm_request during process_llm_request
The tool correctly uses the custom model for LLM calls while maintaining other request parameters
**Unit Tests:**
- [X] I have added or updated unit tests for my change.
- [X] All unit tests pass locally.
(base) wanglu2:adk-python/ (feature/allow-google-search-tool-set-different-llm✗) $ uv run pytest ./tests/unittests/tools/test_google_search_tool.py [22:07:32]
======================================================================== test session starts ========================================================================
platform darwin -- Python 3.13.1, pytest-9.0.2, pluggy-1.6.0
rootdir: /Users/wanglu2/Documents/Git/adk-python
configfile: pyproject.toml
plugins: mock-3.15.1, anyio-4.12.0, xdist-3.8.0, asyncio-1.3.0, langsmith-0.6.0
asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function
collected 21 items
tests/unittests/tools/test_google_search_tool.py ..................... [100%]
======================================================================== 21 passed in 7.91s =========================================================================
### Checklist
- [X] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [X] I have performed a self-review of my own code.
- [X] I have commented my code, particularly in hard-to-understand areas.
- [X] I have added tests that prove my fix is effective or that my feature works.
- [X] New and existing unit tests pass locally with my changes.
- [X] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
### Additional context
Co-authored-by: Kathy Wu <wukathy@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4136 from lwangverizon:feature/allow-google-search-tool-set-different-llm 239ea9577bd7befc9a3574aca48dc8243d55192c
PiperOrigin-RevId: 859265757
This change introduces a `flush` method to the `BigQueryAgentAnalyticsPlugin`. This ensures that all pending log events are written to BigQuery before the agent's run completes.
Key changes:
- Added `flush()` method to `BigQueryAgentAnalyticsPlugin` to force write of pending events.
PiperOrigin-RevId: 859263853
Update the litellm version constraint in both project dependencies and dev dependencies to exclude versions 1.81.0 and higher because unit test breakages in GitHub actions introduced by it.
This is a stopgap before the actual fix is added. Close#4225
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 859239880
Bug: In live streaming mode, when function_call and function_response events
arrive during active transcription, they are correctly buffered but never
yielded to the caller. This causes callers to miss these events even though
they are saved to the session.
Fix: Add yield buffered_event after appending buffered events to the session
when transcription ends.
Testing:
- Added unit test: test_live_streaming_buffered_function_call_yielded_during_transcription
- Test verifies buffered events are yielded by:
1. Simulating partial transcription (triggers buffering)
2. Sending function_call during transcription (gets buffered)
3. Ending transcription (should yield buffered events)
4. Asserting both function_call and function_response are in yielded events
Test results:
- With fix: PASSED
- Without fix (yield commented out): FAILED with "Buffered function_call event was not yielded"
- Example event flow after fix:
EVENT: partial=True, input_transcription="Show me the weather"
EVENT: function_call=get_weather, args={'location': 'NYC'} <- Now yielded
EVENT: function_response=get_weather, response={...} <- Now yielded
EVENT: partial=False, input_transcription="Show me the weather for today"
PiperOrigin-RevId: 859158546
This refactors the BigQueryAgentAnalyticsPlugin to use the standard OpenTelemetry API for trace and span ID generation and propagation, replacing the custom ContextVar implementation.
Key changes:
- Utilizes `opentelemetry.trace` for starting/ending spans.
- Correctly uses `opentelemetry.context` for context attachment and detachment.
- Span information is now derived from the OpenTelemetry context when available.
- Added a fallback mechanism to ensure span_id and parent_span_id are still populated if the OpenTelemetry SDK is not initialized.
To get standard OpenTelemetry trace information in BigQuery logs, users should install `opentelemetry-sdk` and initialize a global `TracerProvider` in their application *before* initializing ADK components.
Example minimal initialization:
```python
# Install: pip install opentelemetry-sdk
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
trace.set_tracer_provider(TracerProvider())
```
PiperOrigin-RevId: 858965562
Merge https://github.com/google/adk-python/pull/4175
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
N/A: just fixing typos discovered while reading the repo
**2. Or, if no issue exists, describe the change:**
No code change, just typo fixes: see commit diffs for all details
**Problem:**
Trying to improve overall repo quality
**Solution:**
Fixing typos as they get discovered
### Testing Plan
N/A
**Unit Tests:**
N/A
**Manual End-to-End (E2E) Tests:**
N/A
### Checklist
- [X] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [X] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [X] New and existing unit tests pass locally with my changes.
- [ ] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4175 from didier-durand:fix-typos-c 16e93ed2d9bc153fa0332ab1ae39633fcc5056e9
PiperOrigin-RevId: 858751240
LiteLLM defaults to DEV mode, which automatically loads environment variables from a local `.env` file. This change sets LITELLM_MODE to PRODUCTION to prevent LiteLLM from implicitly loading `.env` files when used within ADK.
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 858723362
This change introduces a helper function `_redact_uri_for_log` to sanitize URIs before logging. It removes user credentials from the netloc and redacts the values of query parameters, ensuring that sensitive information like passwords is not exposed in log outputs. The function is applied to all log statements and error messages that include service URIs for session, memory, and artifact services
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 858703465
The migration tool uses synchronous SQLAlchemy engines but users often provide async driver URLs (e.g., postgresql+asyncpg://) since that's what ADK requires at runtime.
This fix:
- Makes `to_sync_url()` public in `_schema_check_utils.py` for reuse
- Updates `migrate_from_sqlalchemy_pickle.py` to convert async URLs
- Updates `migrate_from_sqlalchemy_sqlite.py` to convert async URLs
- Adds comprehensive unit tests for `to_sync_url()` function
- Adds integration test for migration with async driver URLs
Fixes#4176
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 858359061
Right now the regex is over-matching and is returning true for references like these:
from ..utils._client_labels_utils import EVAL_CLIENT_LABEL
Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 857255767
### Description of Change
**Problem:**
The `ToolboxToolset` was relying on the legacy `toolbox-core` package. Users wanting to use the Toolbox features were forced to install the heavy `[extensions]` group, lacking a granular installation option. Additionally, `ToolboxToolset` had a validation check enforcing either `toolset_name` or `tool_names` to be present, preventing the default behavior of loading all tools (which `toolbox-adk` supports).
**Solution:**
* Refactored `ToolboxToolset` to delegate to `toolbox-adk`.
* Added a new `toolbox` optional dependency group in `pyproject.toml`.
* Users can now run `pip install google-adk[toolbox]` to install only the necessary dependencies.
* Updated the `extensions` dependency group to replace `toolbox-core` with `toolbox-adk`.
* This ensures existing users of `[extensions]` are not broken upon upgrade.
* Removed the restrictive validation check to allow default loading of all tools.
* Updated the `ImportError` message to guide users toward the new granular installation command.
### Testing Plan
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
**Manual End-to-End (E2E) Tests:**
- Verified that the sample agent runs correctly with `toolbox-adk` locally.
- Verified that `ToolboxToolset` can now be instantiated without arguments to load all tools.
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
PiperOrigin-RevId: 857171811
Merge https://github.com/google/adk-python/pull/4117
**Overview**
This PR implements the feature request in #4108 to allow `thinking_config` to be set directly within `generate_content_config`, bringing the Python SDK in line with the Go implementation.
**Changes**
- **llm_agent.py**: Relaxed the validation logic in `validate_generate_content_config` to remove the `ValueError` for `thinking_config`.
- **Precedence Warning**: Added an override of `model_post_init` in `LlmAgent` to issue a `UserWarning` if both a `planner` and a manual `thinking_config` are provided.
- **built_in_planner.py**: Updated `apply_thinking_config` to log an `INFO` message when the planner overwrites an existing configuration on the `LlmRequest`.
**Testing**
Verified with a reproduction script covering:
1. Successful initialization of an agent with direct `thinking_config`.
2. Validation of `UserWarning` during initialization when conflicting configurations are present.
3. Confirmation of logger output when the planner performs an overwrite.
Closes: #4108
Tagging @invictus2010 for visibility.
Co-authored-by: Liang Wu <wuliang@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4117 from Akshat8510:feat/allow-thinking-config-4108 5deeb893799379c681d6822dc4a1e42f86d3ed01
PiperOrigin-RevId: 856821447
Currently only tool calling supports MCP auth. This refactors the auth logic into a auth_utils file and uses it for tool listing as well. Fixes https://github.com/google/adk-python/issues/2168.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 856798589
Merge https://github.com/google/adk-python/pull/4059
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #3961
**Problem:**
Excessive notifications from periodic workflow runs (every 6 hours for triage, daily for stale-bot and docs upload) in forks where they are not needed.
**Solution:**
Add repository checks to prevent scheduled workflows from running in forked repositories.
The workflows will now only run in the main google/adk-python repository.
### Testing Plan
I think that unit tests and E2E are not needed because this change is for GitHub Actions (not ADK source code).
_Please describe the tests that you ran to verify your changes. This is required
for all PRs that are not small documentation or typo fixes._
**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [ ] All unit tests pass locally.
_Please include a summary of passed `pytest` results._
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [ ] New and existing unit tests pass locally with my changes.
- [ ] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4059 from ftnext:disable-fork-actions 991cc94674cd5cef2e3c2aacf243ba7dae7b88ad
PiperOrigin-RevId: 856691019
Merge https://github.com/google/adk-python/pull/3988
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: https://github.com/google/adk-python/issues/3987
- Related: https://github.com/google/adk-python/issues/3596
**2. Or, if no issue exists, describe the change:**
**Problem:**
Idea about my use case
I'm building the report generation system using google-ask (1.18.0) and building multiple subagents here, I'm passing the one subagent Agent as a tool to another Parent Agent. Note: Sub-agent can do web search.
here, parent agent triggers multiple sub-agent (same agent) multiple times according to use case or complexity of the user input
Describe the bug
here, the bug sometimes sub agents doesn't provide the proper output and resulted in the
```
merged_text = '\n'.join(p.text for p in last_content.parts if p.text)
^^^^^^^^^^^^^^^^^^
TypeError: 'NoneType' object is not iterable
and it's breaking the system of Agents workflow
```
**Solution:**
Creating fallback if there is no **last_content.parts** it will return the empty parts so we won't face the NoneType issue
### Testing Plan
Created a unit test file for this issue
test_google_search_agent_tool_repro.py
**Unit Tests:**
- [X] I have added or updated unit tests for my change.
- [X] All unit tests pass locally.
_Please include a summary of passed `pytest` results._
3677 passed, 2208 warnings in 42.64s
**Manual End-to-End (E2E) Tests:**
N/A
### Checklist
- [X] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [X] I have performed a self-review of my own code.
- [X] I have commented my code, particularly in hard-to-understand areas.
- [X] I have added tests that prove my fix is effective or that my feature works.
- [X] New and existing unit tests pass locally with my changes.
- [X] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
### Additional context
N/A
Co-authored-by: Liang Wu <wuliang@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3988 from ananthanarayanan-28:none-type-issue e6ba948345adfc5ac73a5e39d11c68236f117179
PiperOrigin-RevId: 856515019
Original codes use tool.__name__ to register streaming tools, this is problemetic, it only works with python function passed as tools directly, if they are wrapped in FunctionTool, then FunctionTool doesn't have "__name__" property. canonical_tools wrap python function in FunctionTool uniformly thus we can use tool.name uniformly
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 856472936
Merge https://github.com/google/adk-python/pull/4025
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes:
- #3950
- #3731
- #3708
**2. Or, if no issue exists, describe the change:**
**Problem:**
- `ClientSession` of https://github.com/modelcontextprotocol/python-sdk uses AnyIO for async task management.
- AnyIO TaskGroup requires its start and close must happen in a same task.
- Since `McpSessionManager` does not create task per client, the client might be closed by different task, cause the error: `Attempted to exit cancel scope in a different task than it was entered in`.
**Solution:**
I Suggest 2 changes:
Handling the `ClientSession` in a single task
- To start and close `ClientSession` by the same task, we need to wrap the whole lifecycle of `ClientSession` to a single task.
- `SessionContext` wraps the initialization and disposal of `ClientSession` to a single task, ensures that the `ClientSession` will be handled only in a dedicated task.
Add timeout for `ClientSession`
- Since now we are using task per `ClientSession`, task should never be leaked.
- But `McpSessionManager` does not deliver timeout directly to `ClientSession` when the type is not STDIO.
- There is only timeout for `httpx` client when MCP type is SSE or StreamableHTTP.
- But the timeout applys only to `httpx` client, so if there is an issue in MCP client itself(e.g. https://github.com/modelcontextprotocol/python-sdk/issues/262), a tool call waits the result **FOREVER**!
- To overcome this issue, I propagated the `sse_read_timeout` to `ClientSession`.
- `timeout` is too short for timeout for tool call, since its default value is only 5s.
- `sse_read_timeout` is originally made for read timeout of SSE(default value of 5m or 300s), but actually most of SSE implementations from server (e.g. FastAPI, etc.) sends ping periodically(about 15s I assume), so in a normal circumstances this timeout is quite useless.
- If the server does not send ping, the timeout is equal to tool call timeout. Therefore, it would be appropriate to use `sse_read_timeout` as tool call timeout.
- Most of tool calls should finish within 5 minutes, and sse timeout is adjustable if not.
- If this change is not acceptable, we could make a dedicate parameter for tool call timeout(e.g. `tool_call_timeout`).
### Testing Plan
- Although this does not change the interface itself, it changes its own session management logics, some existing tests are no longer valid.
- I made changes to those tests, especially those of which validate session states(e.g. checking whether `initialize()` called).
- Since now session is encapsulated with `SessionContext`, we cannot validate the initialized state of the session in `TestMcpSessionManager`, should validate it at `TestSessionContext`.
- Added a simple test for reproducing the issue(`test_create_and_close_session_in_different_tasks`).
- Also made a test for the new component: `SessionContext`.
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
```plaintext
=================================================================================== 3689 passed, 1 skipped, 2205 warnings in 63.39s (0:01:03) ===================================================================================
```
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [ ] ~~Any dependent changes have been merged and published in downstream modules.~~ `no deps has been changed`
### Additional context
This PR is related to https://github.com/modelcontextprotocol/python-sdk/pull/1817 since it also fixes endless tool call awaiting.
Co-authored-by: Kathy Wu <wukathy@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4025 from challenger71498:feat/task-based-mcp-session-manager f7f7cd0c9c96840361c30499d08c33a189f57d86
PiperOrigin-RevId: 856438147
1. Convert A2A responses containing a DataPart to ADK events. By default, this is done by serializing the DataPart to JSON and embedding it within the inline_data field of a GenAI Part, wrapped with custom tags (<a2a_datapart_json> and </a2a_datapart_json>).
2. Convert ADK events back to A2A requests. Specifically, messages stored in inline_data with the text/plain mime type and content wrapped within the custom tags (<a2a_datapart_json> and </a2a_datapart_json>) are deserialized from JSON back into an A2A DataPart
PiperOrigin-RevId: 856426615
audio is transcribed thus no need to be sent, but other blob(e.g. image) should still be sent.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 856422986
Introduces a function to map LiteLLM finish reason strings to the internal types.FinishReason enum and populates the finish_reason field in LlmResponse. Removes custom logic for handling file URIs, including special casing for different providers, and updates tests accordingly
Close#4125
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 856421317
There was an extra test_mcp_toolset in the tools/ directory with only one test; I moved it into the main file.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 856419611
The LoadArtifactsTool now checks if an artifact's inline data MIME type is supported by Gemini. If not, it attempts to convert the artifact content into a text Part
Close#4028
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 856404510
Explicitly pass the log_level parameter to uvicorn.Config in both
adk web and adk api_server commands. This ensures that Uvicorn's
internal logging respects the configured log level.
Closes#4139
feature/auto-create-new-session
Merge https://github.com/google/adk-python/pull/4072
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**2. Or, if no issue exists, describe the change:**
**Problem:**
When building frontend applications with ADK, there's a limitation where frontends cannot always guarantee that `create_session` is called before initiating a conversation. This creates friction in the user experience because:
- Users may refresh the page or navigate directly to a conversation URL with a specific session_id
- Frontend state management may lose track of whether a session was already created
- Mobile apps or single-page applications have complex lifecycle management where ensuring `create_session` is called first adds unnecessary complexity
- This forces developers to implement additional logic to check session existence before every conversation
Currently, if `get_session` is called with a non-existent session_id, it returns `None`, requiring the frontend to explicitly handle this case and call `create_session` separately.
**Solution:**
Modified the `get_session` method in `DatabaseSessionService` to automatically create a session if it doesn't exist in the database. This "get or create" pattern is common in many frameworks and provides a more developer-friendly API.
The implementation:
1. Attempts to fetch the session from the database
2. If the session doesn't exist (returns `None`), automatically calls `create_session` with the provided parameters
3. Retrieves and returns the newly created session
4. Maintains backward compatibility - existing code continues to work without changes
This allows frontends to simply call `get_session` with a session_id and be confident that the session will be available, regardless of whether it was previously created.
**Benefits:**
- Simplifies frontend integration by removing the need to track session creation state
- Reduces API calls (no need to check existence before calling get_session)
- Follows the principle of least surprise - getting a session with an ID should work reliably
- No breaking changes to existing code that checks for `None` return values
### Testing Plan
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
**pytest results:**
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4072 from lwangverizon:feature/auto-create-new-session 5475c6ae91d12332598d521302736eb1db79a8be
PiperOrigin-RevId: 856019482
LlmResponse so far doesn't expose generation_complete signal, removing the dead codes.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 855835802
### Description of Change
**Problem:**
The `ToolboxToolset` was implemented directly within `adk-python`, leading to code duplication and potential drift from the core `toolbox-adk` implementation.
**Solution:**
Refactored `ToolboxToolset` to act as a rigorous wrapper around the `toolbox-adk` package, which delegates all functionality to `toolbox_adk.ToolboxToolset`.
### Testing Plan
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
Summary:
- Verified initialization flows through to `toolbox-adk`.
- Verified `auth_token_getters` are correctly propagated.
- Verified type hints are static-analysis friendly.
**Manual End-to-End (E2E) Tests:**
Manually verified standard toolbox loading and execution with the new wrapper:
```python
from google.adk.tools import ToolboxToolset
from toolbox_adk import CredentialStrategy
# Loading with toolset_name
ts = ToolboxToolset(
server_url='http://localhost:8080',
toolset_name='calculator',
credentials=CredentialStrategy.toolbox_identity()
)
tools = await ts.get_tools()
print(f'Loaded {len(tools)} tools')
```
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
PiperOrigin-RevId: 855798474
Merge https://github.com/google/adk-python/pull/3756
move event iteration inside api_client context in get_session
Move event iteration inside the api_client context manager in VertexAiSessionService.get_session() to prevent client closure during multi-page event fetching.
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #3757
**2. Or, if no issue exists, describe the change:**
**Problem:**
When a session contains more than 100 events (requiring pagination), `VertexAiSessionService.get_session()` fails with:
```
RuntimeError: Cannot send a request, as the client has been closed.
```
The root cause is that the `events_iterator` is consumed **outside** the `async with self._get_api_client() as api_client:` context block. When the iterator needs to fetch page 2, 3, etc., the API client has already been closed because the `async with` block has exited.
```python
# Current buggy flow:
async with self._get_api_client() as api_client:
get_session_response, events_iterator = await asyncio.gather(...)
# ← Client closed here
async for event in events_iterator: # ← Fails on page 2+ (client closed)
session.events.append(...)
```
**Solution:**
Move the session creation, user validation, and event iteration **inside** the `async with` block so the API client remains open during the entire pagination process:
```python
async with self._get_api_client() as api_client:
get_session_response, events_iterator = await asyncio.gather(...)
# Validation and session creation...
async for event in events_iterator: # ← Now works for all pages
session.events.append(...)
# Client closed after all events are fetched
```
### Testing Plan
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
```bash
pytest tests/unittests/sessions/test_vertex_ai_session_service.py -v
```
**Added regression test:** `test_get_session_pagination_keeps_client_open`
- Creates a `MockAsyncClientWithPagination` that tracks whether it's inside the `async with` context
- Raises `RuntimeError` if iteration happens outside the context (matching real httpx behavior)
- Simulates 3 pages of events (100 + 100 + 50 = 250 events)
- Verifies all 250 events are successfully retrieved
**Manual End-to-End (E2E) Tests:**
1. Deploy an ADK agent to Vertex AI Agent Engine
2. Create a session and send 100+ messages to accumulate >100 events
3. Verify `get_session()` successfully retrieves all events without error
**Before fix:**
```
RuntimeError: Cannot send a request, as the client has been closed.
```
**After fix:**
- Session with 201 events (3 pages) loads successfully
- All events are retrieved and appended to the session
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
### Additional context
This bug affects any production deployment where users have extended conversations. Sessions accumulating >100 events (which triggers pagination) become completely unusable as the agent cannot load the session to process new messages.
The fix is minimal and maintains backward compatibility - it only changes the scope of the `async with` block without altering any logic or return values.
**Affected versions:** Tested on google-adk 1.19.0, but the bug exists in earlier versions as well.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3756 from AlexisMarasigan:fix/vertex-ai-session-service-paginatio 01fbafa6524312f24f7c9feaffb07bff0ad49b77
PiperOrigin-RevId: 855451813
* **Async Safety:** Improved TraceManager context variable handling to ensure correct context isolation in concurrent asynchronous operations. This was achieved by using immutable tuples for the span stack and making copies of context dictionaries before modification.
* **Enhanced Logging:** The BigQueryAgentAnalyticsPlugin now captures richer metadata, including:
* Root agent name (via a new context variable).
* LLM model name and version.
* Usage metadata from LLM requests and responses.
* **Serialization Fix:** Updated BigQueryAgentAnalyticsPlugin to prevent JSON serialization errors when logging custom objects (e.g., Dataclasses). These are now automatically converted to dictionaries or string representations to ensure successful insertion into BigQuery.
PiperOrigin-RevId: 855415320
gcloud auth team requested that we audit ADK's codebase for places where ADC (google.auth.default) is used, and make sure that the quota project id header is being populated.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 855322964
When content capture is disabled, trace attributes for tool arguments, tool responses, LLM requests, LLM responses, and agent data are now set to the string '{}' instead of an empty dictionary
Close#4094
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 855304806
Merge https://github.com/google/adk-python/pull/3999
The AgentSkill in an A2A AgentCard expects examples to be a list of queries as strings. Therefore, agent examples, e.g., as provided by an ExampleTool, must be converted.
This change performs that extraction of just the inputs and converting them to a string to add to the AgentSkill.
### Testing Plan
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
**Manual End-to-End (E2E) Tests:**
Create an agent with ExampleTool and use agent card builder to create agent card for that agent. Fails without this change, succeeds with change included.
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3999 from timn:timn/fix-a2a-examples-from-tool 34c727c3311d2ec945efa3eec652d9e28b6ae2a9
PiperOrigin-RevId: 855288587
this is the only place we made the assertion , all other place called the method on live request queue directly. Also we make sure in runners that live request queue is set.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 855285070
This change updates how `file_data.file_uri` parts are converted to LiteLLM content. For providers like OpenAI and Azure, only URIs resembling OpenAI file IDs ("file-...") are passed as file objects. Other URIs are converted to a text placeholder
Close#4038
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 855277306
The fix will use quotes to escape "key", which is column name in the metadata table. Should work for different database types.
Merge https://github.com/google/adk-python/pull/4106
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4106 from DineshThumma9:fix/mysql-reserved-keyword-issue e39d0d02f3695d6890bc3267417b5dad58f7e8ee
PiperOrigin-RevId: 854411915
Introduces `full_history_when_stateless` to RemoteA2aAgent. When True, stateless agents will receive all session events on each request, instead of only events since their last reply. This allows stateless agents to have access to the complete conversation history.
PiperOrigin-RevId: 854400798
Merge https://github.com/google/adk-python/pull/3745
This change enables Agent Engine deployments to use App objects with event compaction and context caching configs while using the Agent Engine resource name for session operations, rather than App.name.
- Allow app_name parameter to override app.name when both are provided
- Still error when app and agent are both provided (prevents confusion)
- Updated tests to reflect new behavior and added test for override case
- Updateed documentation to clarify the new usage pattern
This fixes the issue where App.name (a simple identifier) conflicts with Agent Engine's requirement for resource names in session creation.
Related to issue #3715
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #3715
- Related: #3715
**2. Or, if no issue exists, describe the change:**
_If applicable, please follow the issue templates to provide as much detail as
possible._
**Problem:**
When deploying an agent to Agent Engine with event compaction and/or context caching enabled, users must wrap their agent in an `App` object to configure these features. However, when the `App` is passed to `AdkApp` and deployed, session creation fails because:
1. `App.name` is validated as a simple Python identifier (e.g., `"my_agent_name"`) via `validate_app_name()`
2. Agent Engine expects the app name to be either a full Reasoning Engine resource name (e.g., `"projects/123/locations/us-central1/reasoningEngines/456"`) or the reasoning engine ID
3. When an `App` object is passed to `AdkApp`, the deployment stores `App.name` (the simple identifier), but session creation later rejects it as invalid
This prevents users from deploying to Agent Engine with event compaction or context caching enabled.
**Solution:**
Allow the `app_name` parameter in `Runner.__init__()` to override `app.name` when both are provided. This enables Agent Engine (and other deployment scenarios) to:
- Pass the full `App` object to preserve event compaction and context caching configurations
- Override `app.name` with the Agent Engine resource name for session operations
- Successfully create sessions using the resource name while maintaining App-level features
The change is backward compatible: existing code that only provides `app` continues to use `app.name` as before. The override only applies when `app_name` is explicitly provided along with `app`.
### Testing Plan
_Please describe the tests that you ran to verify your changes. This is required
for all PRs that are not small documentation or typo fixes._
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
1. **Updated existing test** (`test_runner_init_raises_error_with_app_and_agent`):
- Changed from testing `app` + `app_name` + `agent` error to testing only `app` + `agent` error
- Verifies that `app` and `agent` cannot both be provided (prevents confusion)
2. **Added new test** (`test_runner_init_allows_app_name_override_with_app`):
- Verifies that `app_name` can override `app.name` when both are provided
- Confirms that `runner.app_name == "override_name"` while `runner.app` still references the original App object
- Ensures all App configs (agent, plugins, context_cache_config, etc.) are preserved
```
pytest tests/unittests/test_runners.py::TestRunnerWithPlugins::test_runner_init_raises_error_with_app_and_agent -v
pytest tests/unittests/test_runners.py::TestRunnerWithPlugins::test_runner_init_allows_app_name_override_with_app -v
```
tests/unittests/test_runners.py::TestRunnerWithPlugins::test_runner_init_allows_app_name_override_with_app PASSED [100%]
tests/unittests/test_runners.py::TestRunnerWithPlugins::test_runner_init_raises_error_with_app_and_agent PASSED [100%]
**Manual End-to-End (E2E) Tests:**
1. Create an agent with event compaction and context caching:
```python
from google.adk import Agent
from google.adk.apps import App
from google.adk.apps import EventsCompactionConfig
from google.adk.agents import ContextCacheConfig
root_agent = Agent(
name="my_agent",
model="gemini-2.5-flash",
instruction="You are a helpful assistant.",
)
app = App(
name="my_agent",
root_agent=root_agent,
events_compaction_config=EventsCompactionConfig(
compaction_interval=2,
overlap_size=1,
),
context_cache_config=ContextCacheConfig(),
)
```
2. Create a Runner with app and override app_name:
```python
from google.adk import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.artifacts import InMemoryArtifactService
runner = Runner(
app=app,
app_name="projects/123/locations/us-central1/reasoningEngines/456", # Resource name
session_service=InMemorySessionService(),
artifact_service=InMemoryArtifactService(),
)
# Verify app_name override worked
assert runner.app_name == "projects/123/locations/us-central1/reasoningEngines/456"
assert runner.app == app # Original app object preserved
assert runner.context_cache_config is not None # Config preserved
assert runner.app.events_compaction_config is not None # Config preserved
```
3. Verify session creation uses the overridden name:
```python
session = await runner.session_service.create_session(
app_name=runner.app_name, # Uses resource name, not app.name
user_id="test_user",
)
```
**Expected Results:**
- Runner creation succeeds with both `app` and `app_name` provided
- `runner.app_name` equals the provided `app_name` (not `app.name`)
- All App configurations (event compaction, context caching) are preserved
- Session creation uses the overridden `app_name`
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
### Additional context
**Backward Compatibility:**
This change is fully backward compatible. All existing code patterns continue to work:
- `Runner(app=my_app)` → Still uses `app.name`
- `Runner(app_name="x", agent=my_agent)` → Still works
- `Runner(app=my_app, app_name=None)` → Still works (uses `app.name`)
**Impact on Agent Engine:**
This change enables Agent Engine deployments to support event compaction and context caching. Once this PR is merged, Agent Engine SDK should:
1. Accept `App` objects from `AdkApp(app=my_app, ...)`
2. Create `Runner` with both `app` and `app_name` (resource name):
```python
runner = Runner(
app=my_app, # Preserves event_compaction_config and context_cache_config
app_name=resource_name, # Overrides app.name for session operations
session_service=session_service,
...
)
```
3. Event compaction and context caching will work automatically once the App is passed correctly.
**Related Documentation:**
- Event compaction is documented in `src/google/adk/apps/compaction.py`
- Context caching is documented in `src/google/adk/agents/context_cache_config.py`
- The Runner's App support is documented in `src/google/adk/runners.py`
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3745 from sarojrout:feat/agent-engine-app-name-override 22d91d59df1460d25d06a71e155ad3dc20a69ca8
PiperOrigin-RevId: 854325898
When converting a `types.Content` to LiteLLM messages, if the content contains both `function_response` parts and other types of parts (e.g., text, image), the function now generates a list of LiteLLM messages
Close#4091
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 854240746
The SqliteSessionService now accepts database paths in the form of SQLite URLs (e.g., "sqlite:///./sessions.db", "sqlite+aiosqlite:////absolute.db")
Close#4077
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 853922433
API registry uses a nextPageToken for pagination, so we should loop through all the pages by sending the received nextPageToken to subsequent requests until no token is returned. The first page contains 1P MCP servers, and later pages contain 3P customer servers.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 853880449
Fix discovery engine search tool, bigquery agent analytics plugin, and application integration tool to correctly handle the ADC quota project override -- the x-goog-user-project should be set based on the ADC quota project, per gcloud auth team's requirements.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 853841124
- Treat Part(thought=True) as reasoning_content when building assistant messages.
- Add unit tests for thought-only and thought+text cases.
Close#4069
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 853790274
Default session and artifact services to in-memory when running in Cloud Run/Kubernetes (or when agents_dir isn’t writable) to prevent startup failures from attempting to create .adk under read-only/unwritable container paths (e.g. /app/agents/.adk). Local development defaults are unchanged.
- ADK_FORCE_LOCAL_STORAGE=1 to always use .adk defaults
- ADK_DISABLE_LOCAL_STORAGE=1 to always avoid local storage
If local artifact initialization raises PermissionError, fall back to in-memory and log a warning
Close#3907
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 853315459
Currently Live API only allow one response modality although the config is defined as a list.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 853107710
LlmAgent now resolves model from ancestors or a system default (gemini-2.5-flash) when unset. Added LlmAgent.set_default_model() to override the default globally
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 853006116
The `adk create` command now checks if the provided agent name is a valid Python identifier. An invalid name, such as one containing hyphens, will raise a `click.BadParameter` error before any files are created.
Close#3977
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 853001295
Before Python 3.10, asyncio.Queue() required a running event loop at creation time. This was deprecated in 3.8-3.9 and fully removed in 3.10. ADK requires Python 3.10+, thus remove this unecessary logic
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 852989791
This change introduces a `_sanitize_schema_types` method to the OpenAPI spec parser. This method recursively removes or filters out non-standard schema types (e.g., "Any", "Unknown") from the OpenAPI specification
Close#3704Close#3108
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852986491
Final part of https://github.com/google/adk-python/discussions/3605.
This change introduces:
- A new `adk migrate session` CLI command to run database schema upgrades.
- A migration script to upgrade from the old Pickle-based session schema (v0) to the new JSON-based schema (v1).
- A migration runner that orchestrates the upgrade process, handling sequential migrations and using temporary SQLite databases for intermediate steps if needed.
- Unit tests for the v0 to v1 migration.
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 852983323
This change modifies `load_dotenv_for_agent` to first capture the environment variables already set in the process. After loading the `.env` file with `override=True`, it restores the values of these initially set variables, ensuring that explicitly set environment variables are not overwritten by the `.env` file. A new environment variable, `ADK_DISABLE_LOAD_DOTENV`, is also introduced to completely skip the `.env` loading process
Close#4020
Close $4018
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852981654
Thought parts represent internal model reasoning and should not be included in the content sent back to the model in subsequent turns
Close#3948
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852965417
This change modifies the /run_sse endpoint to split events that contain both content and an artifactDelta. The original event is split into two separate SSE events: one containing only the content (with artifactDelta cleared) and another containing only the artifactDelta (with content cleared)
Close#4036
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852945249
The _load_existing_credential method in CredentialManager will now only attempt to load credentials from the credential service and will no longer check the AuthConfig's exchanged_auth_credential cache.
Close#3772
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852944533
The retry_on_errors decorator in mcp_session_manager.py now catches asyncio.CancelledError and re-raises it immediately, ensuring that cancellation requests are not suppressed or retried
Close#4009
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852468382
The `model_dump_json()` method already returns a JSON string, so wrapping it in `json.dumps()` was causing double encoding
Close#3993
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852455534
Adds a method to merge custom metadata from the RunConfig into each Event. This metadata is applied to events generated by the agent, early exit events, and the initial user message event.
Close#3953
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852433171
These changes add extra hint for the LLM in the `execute_tool` SQL examples to always use back-ticks around BQ project, dataset and table names in the generated SQL, to save the SQL parsing error when the name has special characters.
PiperOrigin-RevId: 852418943
Adds a Pydantic field validator to ToolTrajectoryCriterion to automatically convert string inputs for the match_type field into the corresponding MatchType enum member
Close#3711
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852415560
websocket disconnection could happen in both sending/receiving text, update the log message to make it less confusing.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 852410439
The change updates the `StorageEvent.to_event` method to use `EventActions.model_validate` when rehydrating the `actions` field. This ensures that nested models within `EventActions`, such as `EventCompaction`, are correctly reconstructed from the stored data
Close#4047
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852408683
When truncating conversation history, make sure function_response messages always have their corresponding function_call included
Close#4027
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852377919
- Add path-safe helpers so all builder filesystem operations stay under <agents_dir>/<app_name> and reject traversal/invalid upload paths.
- Rework /builder/save to support tmp=true writes under <app>/tmp/<app>, promote tmp → app root on final save (preserving tools.py/tools/), then clean up tmp on success.
- Simplify /builder/app/{app_name}/cancel to best-effort delete tmp; update GET /builder/app/{app_name}?tmp=true to auto-recreate tmp from the app root and safely serve requested files.
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852366567
Merge https://github.com/google/adk-python/pull/4041
## Description
This PR fixes false positive stale labels in the `adk_stale_agent`.
Previously, the agent was incorrectly identifying the issue as "stale" because it treated `adk-bot` (acting via PAT) as a human maintainer. Since the username lacks the `[bot]` suffix, administrative alerts (e.g., "Notification: The author has updated...") were counted as maintainer activity, inadvertently triggering the stale logic immediately after an author's edit.
## Changes Made
- **Hardcoded Bot Exclusion:** Added `BOT_NAME = "adk-bot"` and updated history parsing loops (comments, edits, timeline) to explicitly ignore this actor.
- **Bot Alert Skip:** Added logic to `continue` (skip) processing the bot's specific "Notification" comment so it is not recorded as the last activity on the timeline.
Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4041 from ryanaiagent:fix/stale-bot-logic f1500a94cb8c9d5090e9b1ef29690506120f7749
PiperOrigin-RevId: 852365962
Detect assistant tool calls that lack matching tool results in the history and insert placeholder tool messages so strict providers don’t reject the request. Prevents crash loops when executions are interrupted mid-tool call.
Close#3971
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852340750
Details:
- Allows users to provide custom instructions for the LLM-backed user simulator via the `custom_instructions` field in `LlmBackedUserSimulatorConfig`.
- The custom instructions must include placeholders for the stop signal, conversation plan, and conversation history. A pydantic validator ensures these placeholders are present.
- If no custom instructions are provided, the current default template is used.
Co-authored-by: Keyur Joshi <keyurj@google.com>
PiperOrigin-RevId: 850471448
The evaluate_invocations method override in Evaluator subclasses was not consistent, leading to errors during calls, especially when using kwargs. Made the overrides and calls consistent to resolve this issue.
Co-authored-by: Keyur Joshi <keyurj@google.com>
PiperOrigin-RevId: 850462752
There isn't a consistent format for MCP server urls in the registry-- some customers add the https:// but others don't. To standardize, only prepend if it isn't there already.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 846451152
This gcloud authentication header is required as a project override when using google ADC credentials. It is required for all OneMCP servers. Originally I manually put it in the big query sample, but since it is used for all OneMCP, it makes sense to just add it to the core API Registry logic. I also refactored the auth header logic a bit to deduplicate.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 845967178
- Stripping whitespace from custom LLM provider and model names when checking for "ollama_chat".
- Enhancing `_flatten_ollama_content` to correctly handle content that is None, a string, a dictionary, or an iterable (like a tuple) of content blocks, not just lists. This aligns with LiteLLM's `OpenAIMessageContent` type being an `Iterable`.
Close#3928
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 845848017
Merge https://github.com/google/adk-python/pull/3932
## Summary
Upgrade GitHub Actions to their latest versions to ensure compatibility with Node 24, as Node 20 will reach end-of-life in April 2026.
## Changes
| Action | Old Version(s) | New Version | Release | Files |
|--------|---------------|-------------|---------|-------|
| `actions/checkout` | [`v5`](https://github.com/actions/checkout/releases/tag/v5) | [`v6`](https://github.com/actions/checkout/releases/tag/v6) | [Release](https://github.com/actions/checkout/releases/tag/v6) | analyze-releases-for-adk-docs-updates.yml, check-file-contents.yml, discussion_answering.yml, isort.yml, pr-triage.yml, pyink.yml, python-unit-tests.yml, stale-bot.yml, triage.yml, upload-adk-docs-to-vertex-ai-search.yml |
## Context
Per [GitHub's announcement](https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-actions-runners/), Node 20 is being deprecated and runners will begin using Node 24 by default starting March 4th, 2026.
### Why this matters
- **Node 20 EOL**: April 2026
- **Node 24 default**: March 4th, 2026
- **Action**: Update to latest action versions that support Node 24
### Security Note
Actions that were previously pinned to commit SHAs remain pinned to SHAs (updated to the latest release SHA) to maintain the security benefits of immutable references.
### Testing
These changes only affect CI/CD workflow configurations and should not impact application functionality. The workflows should be tested by running them on a branch before merging.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3932 from salmanmkc:upgrade-github-actions-node24 0ffbb0b7b5f63d27583f8c24781f2d3ca92c0c23
PiperOrigin-RevId: 845813166
Merge https://github.com/google/adk-python/pull/3933
## Summary
Upgrade GitHub Actions to their latest versions for improved features, bug fixes, and security updates.
## Changes
| Action | Old Version(s) | New Version | Release | Files |
|--------|---------------|-------------|---------|-------|
| `google-github-actions/auth` | [`v2`](https://github.com/google-github-actions/auth/releases/tag/v2) | [`v3`](https://github.com/google-github-actions/auth/releases/tag/v3) | [Release](https://github.com/google-github-actions/auth/releases/tag/v3) | discussion_answering.yml, upload-adk-docs-to-vertex-ai-search.yml |
## Why upgrade?
Keeping GitHub Actions up to date ensures:
- **Security**: Latest security patches and fixes
- **Features**: Access to new functionality and improvements
- **Compatibility**: Better support for current GitHub features
- **Performance**: Optimizations and efficiency improvements
### Security Note
Actions that were previously pinned to commit SHAs remain pinned to SHAs (updated to the latest release SHA) to maintain the security benefits of immutable references.
### Testing
These changes only affect CI/CD workflow configurations and should not impact application functionality. The workflows should be tested by running them on a branch before merging.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3933 from salmanmkc:upgrade-github-actions-node24-general 142ef77d94da42b0f75a1fc810e8deeb666684a4
PiperOrigin-RevId: 845804209
Previously, the warning check occurred after "plugins" could be populated from "app.plugins". This caused the deprecation warning to trigger incorrectly even when plugins were properly provided via the app argument. Moving the check ensures it only triggers when the deprecated plugins argument is explicitly used.
The change also enhanced the condition that would trigger the warning to cover the empty list case.
PiperOrigin-RevId: 845746847
Merge https://github.com/google/adk-python/pull/3937
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
Not applicable
**Problem:**
Several markdown files contained typos, grammatical errors (e.g., "search youtubes"), and awkward phrasing.
**Solution:**
Performed a comprehensive quality assurance pass on the documentation.
- Fixed typos in README.md and AGENTS.md.
- Improved grammar and phrasing in CONTRIBUTING.md and sample READMEs.
### Testing Plan
This is a documentation and typo fix PR.
**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [ ] All unit tests pass locally.
N/A - Documentation changes only.
**Manual End-to-End (E2E) Tests:**
This is a documentation and typo fix PR.
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [ ] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3937 from Goodnight77:docs/fix-typos a0cf4db6741f19c77eeb0746c9db524dd02121ac
PiperOrigin-RevId: 845599254
Merge https://github.com/google/adk-python/pull/3939
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
n/a
**2. Or, if no issue exists, describe the change:**
**Problem:**
In the Community Repo section of README.md, there was a missing space between the markdown link `[adk-python-community repo](...)` and the word `that`, causing the text to render as `repo](...)that` instead of `repo](...) that`.
**Solution:**
Add a single space between the closing parenthesis of the markdown link and the word "that" to fix the typo.
### Testing Plan
**Unit Tests:**
This is a small documentation/typo fix. No code changes were made.
**Manual End-to-End (E2E) Tests:**
I verified that the markdown renders correctly with proper spacing between the link and following text.
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
### Additional context
This is a minor typo fix in the README.md file. No functional changes.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3939 from hiroakis:fix-readme-typo f4e8014367961b55124da57b5c910890a287b2af
PiperOrigin-RevId: 845595505
Part 2 of https://github.com/google/adk-python/discussions/3605.
The DatabaseSessionService now checks for the usage of a V1 schema based on the "adk_internal_metadata" table. Table creation and subsequent operations use either the V0 or V1 SQLAlchemy models accordingly. New databases will default to V1.
Migration script and CLI command will be provided in the next change.
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 845443406
Part 1 of https://github.com/google/adk-python/discussions/3605.
This change adds a new schema that uses JSON serialization to store Events data in the database. A new "adk_internal_metadata" table is also added to store information like schema version. Since we want to keep supporting existing DB, we fork from the original schema and call it "v0", while the new one is called "v1".
The change is no-op for existing users. In later change, the new schema will be used for new databases, and migration scripts will be provided for existing databases.
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 844986248
Merge https://github.com/google/adk-python/pull/3917
To migrate from existing DB :
ALTER TABLE events ALTER COLUMN error_message TYPE TEXT; -- PostgreSQL
ALTER TABLE events MODIFY error_message TEXT; -- MySQL
SQLite: Doesn't enforce VARCHAR length limits anyway. No impact.
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
n/a
**2. Or, if no issue exists, describe the change:**
**Problem:**
When storing events with error messages longer than 1024 characters using `DatabaseSessionService`, PostgreSQL raises:
```
ERROR: value too long for type character varying(1024)
```
The `error_message` column in `StorageEvent` is defined as `String(1024)`, which maps to `VARCHAR(1024)`. Error messages can exceed 1024 characters.
**Solution:**
Change the column type from `String(1024)` to `Text` to allow unlimited length error messages.
### Testing Plan
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
$ pytest ./tests/unittests/sessions/ -v
======================= 75 passed, 3 warnings in 26.92s ========================
**Manual End-to-End (E2E) Tests:**
- Verified that events with long error messages (>1024 chars) can be stored in PostgreSQL
- Verified backward compatibility with existing databases
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
### Additional context
This is a minimal change (1 line) that only affects the `error_message` column type definition.
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3917 from hiroakis:main 1474fd552cdbd7206de383e5507fd8a733aecda1
PiperOrigin-RevId: 844845692
This change ensures that file URI parts passed to LiteLLM always include a "format" field. If `mime_type` is not explicitly provided in `FileData`, the system attempts to infer it from the URI's file extension. If inference fails, a default "application/octet-stream" is used. This is necessary because LiteLLM's Vertex AI backend requires the "format" field for GCS URIs.
Close#3787
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 843753810
Merge https://github.com/google/adk-python/pull/2870
## Summary
Add `token_endpoint_auth_method` field to OAuth2Auth class to allow configuring OAuth2 token endpoint authentication methods. This enables users to specify how the client should authenticate with the authorization server's token
endpoint.
• Add `token_endpoint_auth_method` field to `OAuth2Auth` with default value `"client_secret_basic"`
• Update `create_oauth2_session()` to pass the authentication method to `OAuth2Session`
• Maintain backward compatibility with existing OAuth2 configurations
## Unit Tests
Added unit test coverage with 3 new test methods:
1. `test_create_oauth2_session_with_token_endpoint_auth_method()` - Tests explicit auth method setting (`client_secret_post`)
2. `test_create_oauth2_session_with_default_token_endpoint_auth_method()` - Tests default behavior (`client_secret_basic`)
3. `test_create_oauth2_session_oauth2_scheme_with_token_endpoint_auth_method()` - Tests with OAuth2 scheme using `client_secret_jwt`
**Test Results:**
✅ 16/16 OAuth2 credential utility tests passed
✅ 240/240 auth module tests passed (no regressions)
✅ Tests cover both GOOGLE_AI and VERTEX variants
✅ Pylint score: 9.41/10
## Changes Made
**src/google/adk/auth/auth_credential.py**
- Added `token_endpoint_auth_method: Optional[str] = "client_secret_basic"` to `OAuth2Auth` class
**src/google/adk/auth/oauth2_credential_util.py**
- Updated `create_oauth2_session()` to pass `token_endpoint_auth_method` parameter to `OAuth2Session`
**tests/unittests/auth/test_oauth2_credential_util.py**
- Added 3 comprehensive test methods covering different authentication scenarios
## Backward Compatibility
✅ **Non-breaking change** - All existing OAuth2 configurations continue to work unchanged with the default `client_secret_basic` authentication method.
## Supported Authentication Methods
- `client_secret_basic` (default) - Client credentials in Authorization header
- `client_secret_post` - Client credentials in request body
- `client_secret_jwt` - JWT with client secret
- `private_key_jwt` - JWT with private key
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2870 from sully90:feat/oauth2-token-endpoint-auth-method 04fe8244598f96b4e3366f0fc79382628382e9c2
PiperOrigin-RevId: 843739984
LiteLLM's StreamHandlers output to stderr by default. In cloud environments like GCP, stderr output is treated as ERROR severity regardless of actual log level, causing INFO-level logs to be incorrectly classified as errors.
This change redirects LiteLLM loggers to stdout in two places:
- In `lite_llm.py`: Immediately after litellm import
- In `logs.py`: When `setup_adk_logger()` is called (with guard to check if litellm is imported)
Close#3824
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 843393874
LiteLLM's `ollama_chat` provider does not accept array-based content in messages. This change flattens multipart content by joining text parts or JSON-serializing non-text parts before sending the request to the LiteLLM completion API. This ensures compatibility with Ollama's chat endpoint.
Close#3727
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 843382361
The `_to_litellm_response_format` function now adapts the output format based on the provided model. Gemini models continue to use the "response_schema" key, while OpenAI-compatible models (including Azure OpenAI and Anthropic) now use the "json_schema" key as per LiteLLM's documentation for JSON mode. The schema name is also included in the "json_schema" format.
Close#3713Close#3890
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 843326850
Explicitly resolve the GCP project from arguments or environment variables before calling `spanner.Client`. This avoids redundant calls to `google.auth.default()` that newer versions of the Spanner library might make.
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 843320305
Performance: Switched to BigQuery Storage Write API with async batching, reducing agent latency.
Multimodal: Native support for GCS offloading (ObjectRef) for images, video, and large text.
Reliability: Added connection pooling, retries, and a "rescue flush" for safe shutdown on Cloud Run.
Observability: Fixed distributed tracing hierarchy with ContextVars support.
PiperOrigin-RevId: 843062561
This change introduces an add_session_to_memory method to both CallbackContext and ToolContext, allowing agents and tools to explicitly trigger the saving of the current session to the memory service. This enables more fine-grained control over when session data is persisted for memory generation. A ValueError is raised if the memory service is not configured.
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 843021899
Merge https://github.com/google/adk-python/pull/3875
# Problem
The example in `contributing/samples/human_in_loop/README.md` shows:
```python
await runner.run_async(...)
```
However, `run_async` returns an **async generator**, so awaiting it raises:
```
TypeError: object async_generator can't be used in 'await' expression
```
Additionally, the example payload uses `"ticket-id"` while ADK tools and other examples use `"ticketId"`, creating a mismatch that breaks copy/paste usage.
# Solution
- Updated the snippet to consume the async generator correctly:
```python
async for event in runner.run_async(...):
...
```
- Aligned the payload key from `"ticket-id"` → `"ticketId"` for consistency with ADK schema and other examples.
These changes make the example runnable and consistent with the API’s actual behavior.
# Testing Plan
This PR is a **small documentation correction**, so no unit tests are required per contribution guidelines.
- Verified the corrected snippet manually to ensure it no longer raises `TypeError`.
# Checklist
- [x] I have read the CONTRIBUTING.md document.
- [x] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas. *(N/A – docs only)*
- [ ] I have added tests that prove my fix is effective or that my feature works. *(N/A – docs only)*
- [ ] New and existing unit tests pass locally with my changes. *(N/A – docs only)*
- [x] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules. *(N/A)*
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3875 from krishna-dhulipalla:docs/fix-adk-run_async-example 83fc5b430690b63b8b7bf1025ef03b0761264751
PiperOrigin-RevId: 842952362
When users instantiate LlmAgent directly (not subclassed), the origin inference incorrectly detected ADK's internal google/adk/agents/ path as a mismatch.
Use metadata from AgentLoader when available
Skip inference for google.adk.* module
Close#3143
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 842774292
Context: many issues related to local mult-agent system is tagged with a2a
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 842397159
Add using the execute sql query return result as list of dictionaries.
In each dictionary the key is the column name and the value is the value of
the that column in a given row.
PiperOrigin-RevId: 840909555
This change introduces a `verify` parameter to `RestApiTool` and `OpenAPIToolset`. This parameter allows users to configure how SSL certificates are verified when making API calls using the `requests` library. Options include providing a path to a CA bundle, disabling verification, or using a custom `ssl.SSLContext`. New methods `configure_verify` and `configure_verify_all` are added to update this setting after initialization. This is useful for environments with TLS-intercepting proxies.
Fixes: https://github.com/google/adk-python/issues/3720
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 840809727
The RemoteA2aAgent now extracts a "task_id" from the custom metadata of the last agent event in the session, alongside the existing "context_id". This task_id is then included in the A2AMessage sent to the remote A2A service.
Close#3765
PiperOrigin-RevId: 840375992
Update fastapi constraint from <0.119.0 to <0.124.0
Update starlette minimum version from >=0.46.2 to >=0.49.1
Closes#3822
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 840372879
When converting `types.Content` with a `function_response` to LiteLLM's `ChatCompletionToolMessage`, if the response is already a string, use it directly. Otherwise, serialize the response to JSON. This prevents double-serialization of string payloads
Close#3676
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 840013822
This change refactors how session, memory, and artifact services are created in the fast_api server, using the shared service_factory.
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 839997110
This change introduces `Gemma3Ollama`, a new LLM model class for running Gemma 3 models locally via Ollama, leveraging LiteLLM. The function calling logic previously in the `Gemma` class has been refactored into a `GemmaFunctionCallingMixin` and is now used by both `Gemma` and `Gemma3Ollama`. A new sample application, `hello_world_gemma3_ollama`, is added to demonstrate using `Gemma3Ollama` with an agent. Unit tests for `Gemma3Ollama` are also included.
Merge: https://github.com/google/adk-python/pull/3120
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 839996879
This change expands the supported file MIME types and introduces provider-specific handling for file uploads. For providers like OpenAI and Azure, inline file data is now uploaded via `litellm.acreate_file` to obtain a `file_id`, which is then used in the message content. Other providers continue to use base64 encoded file data. Affected functions have been updated to be asynchronous
Merge:https://github.com/google/adk-python/pull/2863
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 839996848
The RemoteA2aAgent now extracts a "task_id" from the custom metadata of the last agent event in the session, alongside the existing "context_id". This task_id is then included in the A2AMessage sent to the remote A2A service.
Close#3765
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 839996774
The warning message shows that ADK Web is for development purposes only and should not be used in production, as it has access to all data. This warning is displayed when the `--with-ui` flag is used with `adk deploy` and `adk deploy to-gke`
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 839795361
Merge https://github.com/google/adk-python/pull/3583
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #3582
**2. Or, if no issue exists, describe the change:**
_If applicable, please follow the issue templates to provide as much detail as
possible._
**Problem:**
Currently, the BigQuery tool in ADK does not provide a way for developers to add custom labels to BigQuery jobs created by their agents. This makes it difficult to:
Track and monitor BigQuery costs associated with specific agents or use cases
Organize and filter BigQuery jobs in the Google Cloud Console
Implement billing attribution and resource organization strategies
Differentiate between jobs from different environments (dev, staging, production)
While the tool automatically adds an internal adk-bigquery-tool label with the caller_id, there's no mechanism for users to add their own custom labels for tracking and monitoring purposes.
**Solution:**
Add a labels configuration field to BigQueryToolConfig that allows users to specify custom key-value pairs to be applied to all BigQuery jobs executed by the agent. The solution should:
Configuration Option: Add an optional labels parameter to BigQueryToolConfig accepting a dictionary of string key-value pairs
Validation: Ensure labels follow BigQuery's requirements (non-empty string keys, string values)
Job Application: Automatically apply configured labels to all BigQuery jobs alongside the existing internal labels Documentation: Provide clear documentation on how to use labels for tracking and monitoring
### Testing Plan
_Please describe the tests that you ran to verify your changes. This is required
for all PRs that are not small documentation or typo fixes._
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
_Please include a summary of passed `pytest` results._
```
pytest tests/unittests/tools/bigquery/test_bigquery_tool_config.py -v --tb=line -W ignore::UserWarning
========================================= test session starts ==========================================
platform darwin -- Python 3.11.14, pytest-9.0.1, pluggy-1.6.0 -- *****redacted******
cachedir: .pytest_cache
rootdir: *****redacted******
configfile: pyproject.toml
plugins: mock-3.15.1, anyio-4.11.0, xdist-3.8.0, langsmith-0.4.43, asyncio-1.3.0
asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function
collected 14 items
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_experimental_warning PASSED [ 7%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_invalid_property PASSED [ 14%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_invalid_application_name PASSED [ 21%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_max_query_result_rows_default PASSED [ 28%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_max_query_result_rows_custom PASSED [ 35%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_valid_maximum_bytes_billed PASSED [ 42%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_invalid_maximum_bytes_billed PASSED [ 50%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_valid_labels PASSED [ 57%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_empty_labels PASSED [ 64%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_none_labels PASSED [ 71%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_invalid_labels_type PASSED [ 78%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_invalid_label_key_type PASSED [ 85%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_invalid_label_value_type PASSED [ 92%]
tests/unittests/tools/bigquery/test_bigquery_tool_config.py::test_bigquery_tool_config_empty_label_key PASSED [100%]
==================================================================================================== 14 passed in 2.02s ====================================================================================================
```
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
### Additional context
_Add any other context or screenshots about the feature request here._
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3583 from Faraaz1994:feature/bq_label 0fd7fe6a3b1ee20a36f73562e425d007b8d7dc9d
PiperOrigin-RevId: 839523588
The vector_store_similarity_search tool performs similarity search against data in a Spanner vector store table, using the provided Spanner tool settings for configuration.
PiperOrigin-RevId: 839352057
The Gemini API may not always send an explicit transcription finished signal. This change ensures that any buffered input or output transcription text is yielded as a finished transcription when a turn is completed, generation is complete, or the session is interrupted.
Also, refined the check for `event.partial` in runners.py to be more explicit.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 839008606
LlmAgentConfig.model now accepts either a plain model string or a CodeConfig. This lets YAML configs pass a LiteLLM instance with managed API settings (e.g., api_base and fallbacks) so agents can hit KimiK2’s managed endpoint instead of only the default modelID.
Close#3579
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 838978654
This change adds new `POST` endpoint `/apps/{app_name}/users/{user_id}/sessions/{session_id}/artifacts` to the ADK web server. This endpoint lets clients to save new artifacts associated with a specific session. The endpoint uses `SaveArtifactRequest` and returns `SaveArtifactResponse`, including the version and canonical URI of the saved artifact.
Close#1975
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 838977880
Default CLI session storage to SQLite instead of in-memory
Previously, adk run and adk web used in-memory session storage by default, causing sessions to be lost on restart. Now sessions persist to .adk/session.db automatically. To use in-memory storage, pass --session-service-uri memory://
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 838975328
Merge https://github.com/google/adk-python/pull/3700
### Description
This PR refactors the `adk_stale_agent` to address `429 RESOURCE_EXHAUSTED` errors encountered during workflow execution. The previous implementation was inefficient in fetching issue history (using pagination over the REST API) and lacked server-side filtering, causing excessive API calls and huge token consumption that breached Gemini API quotas.
The new implementation switches to a **GraphQL-first approach**, implements server-side filtering via the Search API, adds robust concurrency controls, and significantly improves code maintainability through modular refactoring.
### Root Cause of Failure
The previous workflow failed with the following error due to passing too much context to the LLM and processing too many irrelevant issues:
```text
google.genai.errors.ClientError: 429 RESOURCE_EXHAUSTED.
Quota exceeded for metric: generativelanguage.googleapis.com/generate_content_paid_tier_input_token_count
```
### Key Changes
#### 1. Optimization: REST → GraphQL (`agent.py`)
* **Old:** Fetched issue comments and timeline events using multiple paginated REST API calls (`/timeline`).
* **New:** Implemented `get_issue_state` using a single **GraphQL** query. This fetches comments, `userContentEdits`, and specific timeline events (Labels, Renames) in one network request.
* **Refactoring:** The complex analysis logic has been decomposed into focused helper functions (_fetch_graphql_data, _build_history_timeline, _replay_history_to_find_state) for better readability and testing.
* **Configurable:** Added GRAPHQL_COMMENT_LIMIT and GRAPHQL_TIMELINE_LIMIT settings to tune context depth
* **Impact:** Drastically reduces the data payload size and eliminates multiple API round-trips, significantly lowering the token count sent to the LLM.
#### 2. Optimization: Server-Side Filtering (`utils.py`)
* **Old:** Fetched *all* open issues via REST and filtered them in Python memory.
* **New:** Uses the GitHub Search API (`get_old_open_issue_numbers`) with `created:<DATE` syntax.
* **Impact:** Only fetches issue numbers that actually meet the age threshold, preventing the agent from wasting cycles and tokens on brand-new issues.
#### 3. Concurrency & Rate Limiting (`main.py` & `settings.py`)
* **Old:** Sequential execution loop.
* **New:** Implemented `asyncio.gather` with a configurable `CONCURRENCY_LIMIT` (set to 3).
* **New:** Added `urllib3` retry strategies (exponential backoff) in `utils.py` to handle GitHub API rate limits (HTTP 429) gracefully.
#### 4. Logic Improvements ("Ghost Edits")
* **New Feature:** The agent now detects "Ghost Edits" (where an author updates the issue description without posting a new comment).
* **Action:** If a silent edit is detected on a stale candidate, the agent now alerts maintainers instead of marking it stale, preventing false positives.
### File Comparison Summary
| File | Change |
| :--- | :--- |
| `main.py` | Switched from `InMemoryRunner` loop to `asyncio` chunked processing. Added execution timing and API usage logging. |
| `agent.py` | Replaced REST logic with GraphQL query. Added logic to handle silent body edits. Decomposed giant get_issue_state into helper functions with docstrings. Added _format_days helper. |
| `utils.py` | Added `HTTPAdapter` with Retries. Added `get_old_open_issue_numbers` using Search API. |
| `settings.py` | Removed `ISSUES_PER_RUN`; added configuration for CONCURRENCY_LIMIT, SLEEP_BETWEEN_CHUNKS, and GraphQL limits. |
| `PROMPT_INSTRUCTIONS.txt` | Simplified decision tree; removed date calculation responsibility from LLM. |
### Verification
The new logic minimizes token usage by offloading date calculations to Python and strictly limiting the context passed to the LLM to semantic intent analysis (e.g., "Is this a question?").
* **Metric Check:** The workflow now tracks API calls per issue to ensure we stay within limits.
* **Safety:** Silent edits by users now correctly reset the "Stale" timer.
* **Maintainability:** All complex logic is now isolated in typed helper functions with comprehensive docstrings.
Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3700 from ryanaiagent:feat/improve-stale-agent 888064eff125ae74f7c3a9ad6c74f98de80243a2
PiperOrigin-RevId: 838885530
This change introduces an `AnthropicLlm` base class for direct Anthropic API calls using `AsyncAnthropic`. The existing `Claude` class now inherits from `AnthropicLlm` and is specialized to use `AsyncAnthropicVertex` for models hosted on Vertex AI. The `messages.create` call is now properly awaited
Merge: https://github.com/google/adk-python/pull/2904
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 838851026
This change updates the docstring for `agent_engine_id` to clarify that only the resource ID is expected. It also adds a warning log if the provided `agent_engine_id` contains a '/' character, suggesting it might be a full resource path, and provides guidance on how to extract the ID. Unit tests are added to verify the warning behavior.
Merge: https://github.com/google/adk-python/pull/2941
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 838845022
Also provide a command line tool `adk migrate session` for DB migration
Addresses https://github.com/google/adk-python/discussions/3605
Addresses https://github.com/google/adk-python/issues/3681
To verify:
```
# Start one postgres DB
docker run --name my-postgres -d -e POSTGRES_DB=agent -e POSTGRES_USER=agent -e POSTGRES_PASSWORD=agent -e PGDATA=/var/lib/postgresql/data/pgdata -v pgvolume:/var/lib/postgresql/data -p 5532:5432 postgres
# Connect to an old version of ADK and produce some query data
adk web --session_service_uri=postgresql://agent:agent@localhost:5532/agent
# Check out to the latest branch and restart ADK web
# You should see error log ask you to migrate the DB
# Start a new DB
docker run --name migration-test-db \
-d \ --rm \ -e POSTGRES_DB=agent \ -e POSTGRES_USER=agent \ -e POSTGRES_PASSWORD=agent -e PGDATA=/var/lib/postgresql/data/pgdata -v migration_test_vol:/var/lib/postgresql/data -p 5533:5432 postgres
# DB Migration
adk migrate session \
--source_db_url="postgresql://agent:agent@localhost:5532/agent" \
--dest_db_url="postgresql://agent:agent@localhost:5533/agent"
# Run ADK web with the new DB
adk web --session_service_uri=postgresql+asyncpg://agent:agent@localhost:5533/agent
# You should see the data from old DB is migrated
```
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 837341139
This calls the cloudapiregistry.googleapis.com API to get MCP tools from the project's registry, and adds them to ADK.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 837166909
Adds the shared adk_services_options decorator to adk run and other commands so developers can pass session/artifact URIs from the CLI
Has new warning for the unsupported memory service on adk run, and removes the legacy --session_db_url/--artifact_storage_uri flags with tests
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 836743358
This change routes adk run and the FastAPI server through the new session/artifact service factory, keeps the default experience backed by per-agent .adk storage
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 836733234
Previously, image parts were always filtered out when converting content to Anthropic message parameters. This change updates the logic to only filter out image parts and log a warning when the content role is not "user". This enables sending image data as part of user prompts to Claude models
Merges: https://github.com/google/adk-python/pull/3286
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 836725196
Merge https://github.com/google/adk-python/pull/3284
**Problem:**
When debugging agents that utilize the `VertexAiSearchTool`, it's currently difficult to inspect the specific configuration parameters (datastore ID, engine ID, filter, max_results, etc.) being passed to the underlying Vertex AI Search API via the `LlmRequest`. This lack of visibility can hinder troubleshooting efforts related to tool configuration.
**Solution:**
This PR enhances the `VertexAiSearchTool` by adding a **debug-level log statement** within the `process_llm_request` method. This log precisely records the parameters being used for the Vertex AI Search configuration just before it's appended to the `LlmRequest`.
This provides developers with crucial visibility into the tool's runtime behavior when debug logging is enabled, significantly improving the **debuggability** of agents using this tool. Corresponding unit tests were updated to rigorously verify this new logging output using `caplog`. Additionally, minor fixes were made to the tests to resolve Pydantic validation errors.
Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3284 from omkute10:feat/add-logging-vertex-search-tool 199c12bf00a57abe202401591088c0423b39b928
PiperOrigin-RevId: 836419886
Merge https://github.com/google/adk-python/pull/2588
## Description
Fixes an issue in `base_llm_flow.py` where, in Bidi-streaming (live) mode, the multi-agent structure causes duplicated responses after tool calling.
## Problem
In Bidi-streaming (live) mode, when utilizing a multi-agent structure, the leaf-level sub-agent and its parent agent both process the same function call response, leading to duplicate replies. This duplication occurs because the parent agent's live connection remains open while initiating a new connection with the child agent.
## Root Cause
The issue originated from the placement of agent transfer logic in the `_postprocess_live` method at lines 547-557. When a `transfer_to_agent` function call was made:
1. The function response was processed in `_postprocess_live`
2. A recursive call to `agent_to_run.run_live` was initiated
3. This prevented the closure of the parent agent's connection at line 175 of the `run_live` method, as that code path was never reached
4. Both the parent and child agents remained active, causing both to process subsequent function responses
## Solution
This PR addresses the issue by ensuring the parent agent's live connection is closed before initiating a new one with the child agent. Changes made:
**Connection Management**: Moved the agent transfer logic from `_postprocess_live` method to the `run_live` method, specifically:
- Removed agent transfer handling from lines 547-557 in `_postprocess_live`
- Added agent transfer handling after connection closure at lines 176-184 in `run_live`
**Code Refactoring**: The agent transfer now occurs in the proper sequence:
1. Parent agent processes the `transfer_to_agent` function response
2. Parent agent's live connection is properly closed (line 175)
3. New connection with child agent is initiated (line 182)
4. Child agent handles subsequent function calls without duplication
**Improved Flow Control**: This ensures that each agent processes function call responses without duplication, maintaining proper connection lifecycle management in multi-agent structures.
## Testing
To verify this fix works correctly:
1. **Multi-Agent Structure Test**: Set up a multi-agent structure with a parent agent that transfers to a child agent via `transfer_to_agent` function call
2. **Bidi-Streaming Mode**: Enable Bidi-streaming (live) mode in the configuration
3. **Function Call Verification**: Trigger a function call that results in agent transfer
4. **Response Monitoring**: Verify that only one response is generated (not duplicated)
5. **Connection Management**: Confirm that parent agent's connection is properly closed before child agent starts
**Expected Behavior**:
- Single function response per call
- Clean agent handoffs without connection leaks
- Proper connection lifecycle management
## Backward Compatibility
This change is **fully backward compatible**:
- No changes to public APIs or method signatures
- Existing single-agent flows remain unaffected
- Non-live (regular async) flows continue to work as before
- Only affects the internal flow control in live multi-agent scenarios
Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2588 from AlexeyChernenkoPlato:fix/double-function-response-processing-issue 3339260a4e007251137d199bdcef0ddef4487b03
PiperOrigin-RevId: 835619170
This change replaces the use of `ChatCompletionDeveloperMessage` with `ChatCompletionSystemMessage` and sets the role to "system" for providing system instructions to LiteLLM models
Close#3657
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 835388738
Merge https://github.com/google/adk-python/pull/3576
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #3557
- Related: #_issue_number_
**2. Or, if no issue exists, describe the change:**
_If applicable, please follow the issue templates to provide as much detail as
possible._
**Problem:**
When creating a BaseAgent with multiple sub-agents, there was no validation to ensure that all sub-agents have unique names. This could lead to confusion when trying to find or reference specific sub-agents by name, as duplicate names would make it ambiguous which agent is being referenced.
**Solution:**
Added a @field_validator for the sub_agents field in BaseAgent that validates all sub-agents have unique names. The validator:
Checks for duplicate names in the sub-agents list
Raises a ValueError with a clear error message listing all duplicate names found
Returns the validated list if all names are unique
Handles edge cases like empty lists gracefully
### Testing Plan
_Please describe the tests that you ran to verify your changes. This is required
for all PRs that are not small documentation or typo fixes._
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
_Please include a summary of passed `pytest` results._
Added 4 new test cases in tests/unittests/agents/test_base_agent.py:
test_validate_sub_agents_unique_names_single_duplicate: Verifies that a single duplicate name raises ValueError
test_validate_sub_agents_unique_names_multiple_duplicates: Verifies that multiple duplicate names are all reported in the error message
test_validate_sub_agents_unique_names_no_duplicates: Verifies that unique names pass validation successfully
test_validate_sub_agents_unique_names_empty_list: Verifies that empty sub-agents list passes validation
All tests pass locally. You can run with:
pytest tests/unittests/agents/test_base_agent.py::test_validate_sub_agents_unique_names_single_duplicate tests/unittests/agents/test_base_agent.py::test_validate_sub_agents_unique_names_multiple_duplicates tests/unittests/agents/test_base_agent.py::test_validate_sub_agents_unique_names_no_duplicates tests/unittests/agents/test_base_agent.py::test_validate_sub_agents_unique_names_empty_list -v
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
Test Case 1: Duplicate names should raise error
from google.adk.agents import Agent
agent1 = Agent(name="sub_agent", model="gemini-2.5-flash")
agent2 = Agent(name="sub_agent", model="gemini-2.5-flash") # Same name
# This should raise ValueError
try:
parent = Agent(
name="parent",
model="gemini-2.5-flash",
sub_agents=[agent1, agent2]
)
except ValueError as e:
print(f"Expected error: {e}")
# Output: Found duplicate sub-agent names: `sub_agent`. All sub-agents must have unique names.
Test Case 2: Unique names should work
from google.adk.agents import Agent
agent1 = Agent(name="agent1", model="gemini-2.5-flash")
agent2 = Agent(name="agent2", model="gemini-2.5-flash")
# This should work without error
parent = Agent(
name="parent",
model="gemini-2.5-flash",
sub_agents=[agent1, agent2]
)
print("Success: Unique names validated correctly")
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
### Additional context
This change adds validation at the BaseAgent level, so it automatically applies to all agent types that inherit from BaseAgent (e.g., LlmAgent, LoopAgent, etc.). The validation uses Pydantic's field validator system, which runs during object initialization, ensuring the constraint is enforced early and consistently.
The error message clearly identifies which names are duplicated, making it easy for developers to fix the issue:
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3576 from sarojrout:feat/validate-unique-sub-agent-names 07adf1f9a5fc935389eb9dfa3cbc1311f551ebe3
PiperOrigin-RevId: 835358118
Merge https://github.com/google/adk-python/pull/3538
Main change from:
E(inv=2, role=user), E(inv=2, role=model), E(inv=2, role=user),
To:
E(inv=2, role=user), E(inv=2, role=model)
I think the last E(inv=2, role=user) was wrong. Also reformatted.
Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3538 from adrianad:patch-1 627b933bdc3e00e45f704edf95448281e32d127c
PiperOrigin-RevId: 835346467
The `database_session_service` now updates the `update_time` of a session to the event's timestamp when an event is appended
Close#2721
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 834994070
LlmResponse/Event now keep both provider reasoning output and the raw vendor payload so callbacks and loggers can inspect hidden “thoughts” or trace bugs without rewriting adapters.
LiteLLM’s adapter and streaming loop emit reasoning chunks alongside text and aggregate them into final events -> all responses now carry a JSON-safe copy of the source payload for debug. UnsafeLocalCodeExecutor uses the documented exec(code, globals, globals) form, letting helper functions defined inside snippets call each other.
Close#1749
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 834956847
Merge https://github.com/google/adk-python/pull/3430
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #3429
**2. Or, if no issue exists, describe the change:**
_If applicable, please follow the issue templates to provide as much detail as
possible._
**Problem:**
The existing `/list-apps` endpoint only returns the name of the folder that each agent is in
**Solution:**
This adds a new endpoint `/list-apps-detailed` which will load each agent using the existing `AgentLoader.load_agent` method, and then return the folder name, display name (with underscores replaced with spaces for a more readable version), description, and the agent type.
This does introduce overhead if you had multiple agents since they all need to be loaded, but by maintaining the existing `/list-apps` endpoint, users can choose which one to hit if they don't want to load all agents. Since the existing `load_agents` method will cache results, there's only a penalty on the first hit.
### Testing Plan
Created a unit test for this, similar to the `/list-apps`. Also tested this with my own ADK instance to verify it loaded correctly.
```
curl --location "localhost:8000/list-apps-detailed"
```
```json
{
"apps": [
{
"name": "agent_1",
"displayName": "Agent 1",
"description": "A test description for a test agent",
"agentType": "package"
},
{
"name": "agent_2",
"displayName": "Agent 2",
"description": "A test description for a test agent ",
"agentType": "package"
},
{
"name": "agent_3",
"displayName": "Agent 3",
"description": "A test description for a test agent",
"agentType": "package"
}
]
}
```
**Unit Tests:**
- [X] I have added or updated unit tests for my change.
- [X] All unit tests pass locally.
3054 passed, 2383 warnings in 46.96s
### Checklist
- [X] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [X] I have performed a self-review of my own code.
- [X] I have commented my code, particularly in hard-to-understand areas.
- [X] I have added tests that prove my fix is effective or that my feature works.
- [X] New and existing unit tests pass locally with my changes.
- [X] I have manually tested my changes end-to-end.
- [X] Any dependent changes have been merged and published in downstream modules.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3430 from dylan-apex:more-detailed-list-apps e6864fd61a673da5fd2fb28d2d7d72cb90f5af0a
PiperOrigin-RevId: 834907771
Merge https://github.com/google/adk-python/pull/3572
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
N/A
**2. Or, if no issue exists, describe the change:**
**Problem:**
Docs fix
### Checklist
- [ ] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [ ] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [ ] New and existing unit tests pass locally with my changes.
- [ ] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3572 from issacg:patch-1 b7c7ed46ff0fb018f4da1537535eff27c323daf5
PiperOrigin-RevId: 834864431
The `Parameter` class now provides default Python names based on the parameter location when the original name is empty. This prevents parameters from having an empty string as their Python name, especially for request bodies defined without a top-level name.
Close#2213
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 834850255
Make sure that the adk run --save_session writes session JSON using the Pydantic camelCase aliases (by_alias=True), matching ADK Web and keeping session files consistent
Close#3558
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 834847209
Merge https://github.com/google/adk-python/pull/3603
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #_issue_number_
- Related: #_issue_number_
**2. Or, if no issue exists, describe the change:**
_If applicable, please follow the issue templates to provide as much detail as
possible._
**Problem:**
_A clear and concise description of what the problem is._
**Solution:**
_A clear and concise description of what you want to happen and why you choose
this solution._
### Testing Plan
_Please describe the tests that you ran to verify your changes. This is required
for all PRs that are not small documentation or typo fixes._
**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [ ] All unit tests pass locally.
_Please include a summary of passed `pytest` results._
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
### Checklist
- [ ] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [ ] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [ ] New and existing unit tests pass locally with my changes.
- [ ] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
### Additional context
_Add any other context or screenshots about the feature request here._
Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3603 from holtskinner:patch-1 833405898b747438e3f8a1b8c34095e25135fca3
PiperOrigin-RevId: 834805195
Retrying only on closed_resource error is not enough to be reliable for production environments due to the other network errors that may occur -- remote protocol error, read timeout, etc. We will update this to retry on all errors. Since it is only a one-time retry, it should not affect latency significantly. Fixes https://github.com/google/adk-python/issues/2561.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 834514264
It also enables the ADK triaging agent to run periodically on planned but not triaged issues.
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 834489103
This change will help the tools user identify per agent job usage in BQ console and INFORMATION_SCHEMA views. This change fulfills the feature request #3582. Here is a demo after change: screen/C6YB4ge2FM2ZREi.
PiperOrigin-RevId: 834480140
When this agent was built before the agent name was changed in the build script and accepted like that from the VB so changed to set into that form
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 834479335
This change introduces `input_transcription` and `output_transcription` fields to session events, enabling the storage and retrieval of transcription data in both the database and Vertex AI session services.
Closes#3172
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 834366848
Fixes https://github.com/google/adk-python/issues/3174
The event compaction process, configured via `EventsCompactionConfig`, was
previously scheduled as a background task using `asyncio.create_task`.
Because Python's `asyncio.create_task` only holds a weak reference to
the created task and no strong reference was maintained by ADK, the
compaction task could be garbage-collected before it finished executing.
This resulted in event compaction failing silently or only partially
running, preventing session history from being summarized.
### Approaches Considered
Two approaches were considered to fix this:
1. **`asyncio.create_task` + Reference:** Create the task with `create_task` and store a strong reference to it (e.g., in a `set` on the [Runner](http://_vscodecontentref_/0) instance), removing it only when complete via `task.add_done_callback()`.
* **Pros:** The [run_async](http://_vscodecontentref_/1) async generator finishes immediately after yielding the last agent event.
* **Cons:** Adds complexity to the Runner state; background task failures are silent to the [run_async](http://_vscodecontentref_/2) caller; requires enhancement to `runner.close()` to correctly manage pending tasks on shutdown.
2. **`await`:** Directly `await` the compaction coroutine at the end of [run_async](http://_vscodecontentref_/3) after all agent events have been yielded.
* **Pros:** Simple to implement; ensures compaction runs to completion; failures during compaction propagate immediately to the [run_async](http://_vscodecontentref_/4) caller, making them visible and easier to debug.
* **Cons:** The `async for` loop iterating over [run_async](http://_vscodecontentref_/5) will not terminate until compaction finishes.
### Decision
This change implements the `await` approach. Although it means the `async for` loop takes longer to terminate when compaction occurs, it was chosen for its **simplicity and robustness**. Ensuring that compaction either succeeds or fails visibly is preferable to silent background failures.
All agent response events are yielded *before* compaction starts, so there is **no user-perceived delay in receiving the agent's answer** for the current turn.
### Integration Note for Users
Because compaction is now awaited, code consuming events via `async for event in runner.run_async(...)` will only finish iterating *after* compaction is complete (if compaction is triggered for that invocation).
If your application only needs the agent's response to proceed (e.g., displaying a message in a UI and allowing the user to reply), you can process events as they arrive and initiate the next turn without waiting for the `async for` loop to fully terminate. A new call to [run_async](http://_vscodecontentref_/6) for the next user query can be made immediately and will execute concurrently.
**Example:**
```python
async def handle_agent_turn(runner, message):
print("Agent is thinking...")
async for event in runner.run_async(user_id='...', session_id='...', new_message=message):
# Stream events to UI, log, etc.
if event.author == 'model' and event.content and event.content.parts[0].text:
print(f"Agent response: {event.content.parts[0].text}")
# The agent has provided a text response.
# The application can now enable user input for the next turn,
# even though this async for loop might not finish immediately
# if compaction is running.
print("Invocation complete (including compaction if any).")
# In your application:
# A new call to handle_agent_turn(runner, next_message) can be made
# as soon as the user provides the next input, without waiting for
# the previous call's generator to be exhausted.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 833885375
this creates service_factory to handle .adk folder changes (including per-agent .adk defaults and in-memory/custom URI handling)
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 833875524
This change loads the agent or app from the specified directory before creating the session. This allows using the correct application name (from the `App` object if applicable) when initializing the session, rather than always defaulting to the folder name. The variable `root_agent` is also renamed to `agent_or_app` to better reflect that it can be either an Agent or an App
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 833839070
Currently logic to check for a disconnected session only checks for certain headers but doesn't detect all cases, leading to situations where it tries to connect to a session that is down. This adds logic so that we ping the server to check if it is disconnected. Fixes https://github.com/google/adk-python/issues/3321.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 833487825
Updates type annotations to use built-in types like `list` and `dict`, and uses `| None` for optional types, along with adding `from __future__ import annotations`
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 832522395
Currently logic to check for a disconnected session only checks for certain headers but doesn't detect all cases, leading to situations where it tries to connect to a session that is down. This adds logic so that we ping the server to check if it is disconnected. Fixes https://github.com/google/adk-python/issues/3321.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 832460068
This update enhances the BigQuery agent analytics plugin:
* **Schema Field Descriptions:** The recommended BigQuery table schema now includes descriptions for each field, improving data understandability.
* **Optimized Table Structure:** The plugin now creates the table with daily partitioning on `timestamp` and clustering on `event_type`, `agent`, and `user_id` by default.
* **Truncation Flag:** A new boolean field `is_truncated` is added to the schema to show if the `content` was truncated.
PiperOrigin-RevId: 832436799
In order to make evals more resilient to temporary model failures, we add retry options to llm_requests that are made during evals.
Note that this is a fall back option, if the developer has already specified their own retry options, then those will be honored.
Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 832383755
Two tools - detect_anomalies and analyze_contribution are modifying the settings passed to them, which is not right as the settings are held and passed by the top level, which means several tools share the same settings.
PiperOrigin-RevId: 832081738
This is ~27% of the current cold start latency after previous changes are submitted. This change refactors `google.adk.tools/__init__.py` to use `__getattr__` for lazy loading of all tools and related classes. Previously, all modules were imported directly upon `google.adk.tools` import, leading to potentially long initial import times. With lazy loading, modules are only imported when they are first accessed, improving the initial startup performance.
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 831537187
This change:
* Deprecates the `save_live_audio` configuration option in `RunConfig`, introducing `save_live_blob` as its replacement. A warning is issued if `save_live_audio` is used.
* Updates `base_llm_flow.py` to use the new `save_live_blob` flag.
* Ensures that audio events generated by `audio_cache_manager.py` are properly appended to the session service.
* Adds a utility script `pcm_audio_player.py` for playing raw PCM audio files.
Input sample event: 14a5859f-6b6c-46ed-9f28-e5008793b1c6|live_bidi_streaming_multi_agent|user|1e867c7f-dbe1-4268-a7bc-7a9fa5fbd16c|e-7a28a060-29bf-4483-bc5c-17248698a897|1762916981.5932|{"content":{"parts":[{"file_data":{"file_uri":"artifact://live_bidi_streaming_multi_agent/user/1e867c7f-dbe1-4268-a7bc-7a9fa5fbd16c/_adk_live/adk_live_audio_storage_input_audio_1762916981593.pcm#0","mime_type":"audio/pcm"}}],"role":"user"},"invocation_id":"e-7a28a060-29bf-4483-bc5c-17248698a897","author":"user","actions":{"state_delta":{},"artifact_delta":{},"requested_auth_configs":{},"requested_tool_confirmations":{}},"id":"14a5859f-6b6c-46ed-9f28-e5008793b1c6","timestamp":1762916981.5932002}
output sample event:
506c9df4-e143-4ebc-90a5-2f5b2eb26754|live_bidi_streaming_multi_agent|user|1e867c7f-dbe1-4268-a7bc-7a9fa5fbd16c|e-7a28a060-29bf-4483-bc5c-17248698a897|1762916986.10579|{"content":{"parts":[{"file_data":{"file_uri":"artifact://live_bidi_streaming_multi_agent/user/1e867c7f-dbe1-4268-a7bc-7a9fa5fbd16c/_adk_live/adk_live_audio_storage_output_audio_1762916986105.pcm;rate=24000#0","mime_type":"audio/pcm;rate=24000"}}],"role":"model"},"invocation_id":"e-7a28a060-29bf-4483-bc5c-17248698a897","author":"model","actions":{"state_delta":{},"artifact_delta":{},"requested_auth_configs":{},"requested_tool_confirmations":{}},"id":"506c9df4-e143-4ebc-90a5-2f5b2eb26754","timestamp":1762916986.105794}
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 831512074
pin crew ai to 3.13 at highest version as it uses chromadb and that uses onnxruntime which does not work yet with 3.14
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 831508884
The change adds an extension point for controlling which request metadata gets attached to A2A requests made by a RemoteAgent.
Instead of taking metadata from custom_metadata of session events users can construct payloads using a2a_request_meta_provider.
request_meta feature was added in v0.3.11 of the a2a-sdk library: https://github.com/a2aproject/a2a-python/releases/tag/v0.3.11
PiperOrigin-RevId: 831506364
This CL adds debug logs to show the history being sent to the live connection and the live connect config used.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 831473597
This changes how content parts are converted for LiteLLM, treating all "text/" mime types as plain text and only "application/pdf" as a file
Close#1940
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 831418696
This is targeting the Client import mostly, but also prevents future latency increase if the other modules in genai adds more 3p dependencies. This change will make ADK only import `live`, `Client` and `_transformers` just-in-time, therefore cutting down cold start latency.
PiperOrigin-RevId: 831244349
This update improves the `BigQueryAgentAnalyticsPlugin` in several ways:
* Corrects the PyArrow schema generation to accurately reflect BigQuery field nullability based on the `mode` attribute.
* Introduces a configurable `shutdown_timeout` in `BigQueryLoggerConfig` to manage how long the plugin waits for pending logs to flush during shutdown.
* Adds more robust error handling within the `shutdown` method and background write tasks, particularly for event loop closure issues.
* Improves internal logging to provide better diagnostics.
* Ensures consistent use of safe content formatting.
PiperOrigin-RevId: 831225837
This change introduces a mechanism for users to register their own custom backend services for sessions, memory, and artifacts without modifying the ADK framework. This enhances the extensibility of ADK.
Two methods of registration are supported, both by placing a file in the parent directory of the agents.
**YAML Configuration (services.yaml or .yml)**
This is the recommended approach for simple services that can be instantiated with a constructor like MyService(uri="...", **kwargs).
Example services.yaml:
```
services:
- scheme: mysession
type: session
class: my_package.my_module.MyCustomSessionService
```
**Python Registration (services.py)**
For services requiring more complex initialization logic, users can define factory functions in a services.py file.
Example services.py
```
from google.adk.cli.service_registry import get_service_registry
from my_package.my_module import MyCustomSessionService
def my_session_factory(uri: str, **kwargs):
# custom initialization logic
return MyCustomSessionService(...)
get_service_registry().register_session_service("mysession", my_session_factory)
```
ADK will load services from services.yaml/.yml first, and then from services.py. If the same service scheme is defined in both, the registration in services.py will take precedence.
To use a registered service, specify its URI via the corresponding command-line flag, e.g., `--session_service_uri=mysession://....`
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 831211371
Creates AdkFolderManager for creating/resetting the .adk layout, helper builders that return SQLite- and filesystembacked services for each agent
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 831206377
Retrying only on closed_resource error is not enough to be reliable for production environments due to the other network errors that may occur -- remote protocol error, read timeout, etc. We will update this to retry on all errors. Since it is only a one-time retry, it should not affect latency significantly. Fixes https://github.com/google/adk-python/issues/2561.
PiperOrigin-RevId: 831153803
The `google.cloud.storage` module is now imported within the `__init__` method of `GCSArtifactService`, rather than at the top level. This avoids importing the potentially heavy `storage` module unless an instance of `GCSArtifactService` is actually created.
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 831124463
This is targeting the Client import mostly, but also prevents future latency increase if the other modules in genai adds more 3p dependencies. This change will make ADK only import `live`, `Client` and `_transformers` just-in-time, therefore cutting down cold start latency.
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 831124329
Retrying only on closed_resource error is not enough to be reliable for production environments due to the other network errors that may occur -- remote protocol error, read timeout, etc. We will update this to retry on all errors. Since it is only a one-time retry, it should not affect latency significantly. Fixes https://github.com/google/adk-python/issues/2561.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 831123085
This change updates `RemoteA2AAgent` to extract and forward custom metadata from session events to the `a2a-sdk`'s `send_message` method. The metadata is looked for under the key `A2A_METADATA_PREFIX + "metadata"` within the `custom_metadata` of the relevant session events. The `a2a-sdk` dependency is also updated to a version that supports this feature.
This feature was added in v0.3.11 of the a2a-sdk library: https://github.com/a2aproject/a2a-python/releases/tag/v0.3.11
PiperOrigin-RevId: 831120978
This change introduces a shutdown lifecycle hook for plugins. The `PluginManager` now has an `async def shutdown()` method that will call `await plugin.shutdown()` on any registered plugins that implement the method. This is called from `Runner.close()`, allowing plugins to perform cleanup tasks like flushing logs or closing connections when the runner instance is being closed. This improves the reliability of plugins that perform background operations.
PiperOrigin-RevId: 831037737
The agent's instructions are updated to guide it to guess a positive integer, starting from 50 and decreasing, using the `guess_number_tool` until the target is found. The maximum number of retries for the `CustomRetryPlugin` is increased from 6 to 10.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 830984481
Merge https://github.com/google/adk-python/pull/2167, during which:
- Let the already added `max_query_result_rows` field cover for `max_downloaded_rows` field added in the PR
- Revert `max_rows` parameter added to execute_sql function, the tool config control should serve most practical use cases
- Keep the relevant tests for tool config
🤖 Generated with [Claude Code](https://claude.ai/code)
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2167 from lupuletic:feature/configurable-max-downloaded-rows 23c56905c297d7aec2be4f1eb86ea23c8178bf21
PiperOrigin-RevId: 830701093
Enhanced `save_artifact` in `callback_context.py` to accept `custom_metadata` and added `get_artifact_version` to retrieve artifact details.
Introduced a new sample, `context_offloading_with_artifact`, demonstrating how to use ADK artifacts to offload large data from the LLM context. The sample includes:
- `QueryLargeDataTool`: Generates mock sales reports, saves them as artifacts with custom metadata, and injects the artifact content into the LLM request immediately after creation.
- `CustomLoadArtifactsTool`: Provides summaries of available artifacts to the LLM based on metadata and loads artifact content on demand when `load_artifacts` is called.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 830592786
Merge https://github.com/google/adk-python/pull/2889
# Implement Full async DatabaseSessionService
**Target Issue:** #1005
## Overview
This PR introduces an asynchronous implementation of the `DatabaseSessionService` with minimal breaking changes. The primary goal is to enable effective use of ADK in fully async environments and API endpoints while avoiding event loop blocking during database I/O operations.
## Changes
- Converted `DatabaseSessionService` to use async/await patterns throughout
## Testing Plan
The implementation has been tested following the project's contribution guidelines:
### Unit Tests
- All existing unit tests pass successfully
- Minor update to test requirements added to support `aiosqlite`
### Manual End-to-End Testing
- E2E tests performed using:
- **LLM Provider:** LiteLLM
- **Database:** PostgreSQL with `asyncpg` driver
```python
from google.adk.sessions.database_session_service import DatabaseSessionService
connection_string: str = (
"postgresql+asyncpg://PG_USER:PG_PSWD@PG_HOST:5432/PG_DB"
)
session_service: DatabaseSessionService = DatabaseSessionService(
db_url=connection_string
)
session = await session_service.create_session(
app_name="test_app", session_id="test_session", user_id="test_user"
)
assert session is not None
sessions = await session_service.list_sessions(app_name="test_app", user_id="test_user")
assert len(sessions.sessions) > 0
session = await session_service.get_session(
app_name="test_app", session_id="test_session", user_id="test_user"
)
assert session is not None
await session_service.delete_session(
app_name="test_app", session_id="test_session", user_id="test_user"
)
assert (
await session_service.get_session(
app_name="test_app", session_id="test_session", user_id="test_user"
)
is None
)
```
The implementation have been also tested using the following configurations for llm provider and Runner:
```python
def get_azure_openai_model(deployment_id: str | None = None) -> LiteLlm:
...
if not deployment_id:
deployment_id = os.getenv("AZURE_OPENAI_DEPLOYMENT_ID")
logger.info(f"Using Azure OpenAI deployment ID: {deployment_id}")
return LiteLlm(
model=f"azure/{os.getenv('AZURE_OPENAI_DEPLOYMENT_ID')}",
stream=True,
)
...
@staticmethod
def _get_runner(agent: Agent) -> Runner:
storage=DatabaseSessionService(db_url=get_pg_connection_string())
return Runner(
agent=agent,
app_name=APP_NAME,
session_service=storage,
)
...
async for event in self.runner.run_async(
user_id=user_id,
session_id=session_id,
new_message=content,
run_config=(
RunConfig(
streaming_mode=StreamingMode.SSE, response_modalities=["TEXT"]
)
if stream
else RunConfig()
),
):
last_event = event
if stream:
yield event
...
```
## Breaking Changes
- Database connection string format may need updates for async drivers
Co-authored-by: Shangjie Chen <deanchen@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2889 from GitMarco27:feature/async_database_session_service e1b1b14934c1fb7975a6832cdd1549e94acab985
PiperOrigin-RevId: 830525148
The tool description now clarifies that `load_artifacts` should be called when a user uploads files, to make those artifacts accessible within the session.
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 830469802
The upper bound for the `fastapi` dependency is adjusted from `<1.119.0` to `<0.119.0`.
Close#3422
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 830465681
Update `_function_declaration_to_tool_param` to use `getattr` when accessing the `required` field within `function_declaration.parameters`. This prevents `AttributeError` when a `FunctionDeclaration`'s parameters schema does not include a `required` attribute
Close#2891
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 830225582
Merge https://github.com/google/adk-python/pull/3352
Replace send() method with send_realtime_input() to fix DeprecationWarning
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #2393
### Testing Plan
Have run unit test for test_live_request_queue.py
**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
Summary :
tests/unittests/agents/test_live_request_queue.py::test_send_realtime PASSED [100%]
**Manual End-to-End (E2E) Tests:**
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
Tested both API variants.
Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3352 from SanjaySiddharth:fix-dep-session.send b23b641a63ff20d1f2dbd9abd519f8facf0aab77
PiperOrigin-RevId: 830182844
Merge https://github.com/google/adk-python/pull/2875
related: https://github.com/google/adk-python/issues/2876
## Reason for this change:
Currently, there is no direct way to access the user_id from within agent contexts, plugins, or callbacks. This limitation prevents several important use cases:
1. **User-specific logging and tracing**: When debugging or monitoring agent behavior, it's crucial to associate actions with specific users for better observability.
2. **User-scoped operations**: Plugins and callbacks often need to perform user-specific operations, such as accessing user-specific resources or applying user-level configurations.
3. **Session management**: The user_id is a key component of session identification, but it's not accessible through the ReadonlyContext interface, requiring workarounds to access it.
## Changes made:
- Added a `user_id` property to the `ReadonlyContext` class in `src/google/adk/agents/readonly_context.py`
- The property exposes the user_id from the underlying invocation context as a readonly field
## Impact:
This change will:
- Enable plugins and callbacks to access the current user's ID directly through the context
- Improve logging and tracing capabilities by allowing user-specific tracking
- Simplify code that needs to perform user-scoped operations without requiring access to internal implementation details
- Maintain backward compatibility as this is an additive change
### Before:
- No direct way to access user_id from ReadonlyContext
### After:
```python
@property
def user_id(self) -> str:
"""The id of the user. READONLY field."""
return self._invocation_context.user_id
```
This is a non-breaking change that adds a new readonly property to the existing ReadonlyContext interface.
Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2875 from ammmr:ammmr-add-user_id-property-to-readonly-context 771734ebf39cb0748a5dc826436236268fbb58f8
PiperOrigin-RevId: 830170908
The new Sqlite version has fixed schema and use a single column to store Event data, this should avoid DB migration for future add to the Event object.
- This change introduces `SqliteSessionService`, an asynchronous session service using `aiosqlite` that stores event data as JSON within SQLite.
- A migration script, `migrate_from_sqlalchemy_sqlite.py`, is included to transition data from the older SQLAlchemy-based SQLite schema to this new format.
- The CLI service registry is updated to use SqliteSessionService for sqlite:// URIs.
- Throw error when user trying to access a legacy DB and advice the user to do the migration.
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 829971174
NOTE:
- This is the expected behavior, so that SSE streaming and non-streaming behaviors are idential to each other in the persisted session.
- The underlying google_llm.py hasn't been fully comply with this behavior, which will be addressed in future changes.
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 829878175
This change updates the `BigQueryAgentAnalyticsPlugin` (formerly in `bigquery_logging_plugin.py`) to perform BigQuery writes asynchronously in background tasks, preventing blocking of the main agent execution flow. Initialization of BigQuery clients and table creation is also made asynchronous. The content logged in various callbacks has been streamlined and simplified. The plugin file has been renamed to `bigquery_agent_analytics_plugin.py` to match the class name.
PiperOrigin-RevId: 829603260
Merge https://github.com/google/adk-python/pull/2600
**Reason for this change:**
Currently, the detailed llm_request object is logged at the info level when connecting to the live API. This causes two main issues:
1. Excessive log output with large instructions: When instructions are large, the unstructured log output becomes problematic. Since the logs are not structured, any
newline characters in the instruction content cause each line to be output as a separate log entry, resulting in massive log output that floods the logging system.
2. Unnecessary verbosity in production: The detailed request information is primarily useful for debugging purposes and should not appear in standard info-level logs,
especially when connections are established frequently.
**Changes made:**
- Changed logger.info to logger.debug in src/google/adk/models/google_llm.py at line 294 for the live connection logging statement.
**Impact:**
This change will:
- Reduce log noise in production environments where info-level logging is enabled
- Keep the detailed connection information available when debug-level logging is needed for troubleshooting
- Improve log readability by showing only essential information at the info level
**Before:**
logger.info('Connecting to live with llm_request:%s', llm_request)
**After:**
logger.debug('Connecting to live with llm_request:%s', llm_request)
This is a non-breaking change that only affects logging verbosity.
Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2600 from ammmr:ammmr-info-to-debug-connect-log 36eab157f5d5ca00b44ee6ad8a4e1aeec871600c
PiperOrigin-RevId: 829596092
We need to set project and location parameters when we instantiate the Google GenAI library Client for VertexAi. This used to work before through environment variables but it doesn't seem to work anymore. So we are updating the `ApigeeLlm` wrapper to read from `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` environment variables and pass to the Client constructor.
PiperOrigin-RevId: 829569362
This trimmed schema includes only the fields relevant to agent shells, tool wiring, and common generation parameters, improving efficiency and focus.
The default model for the assistant has also been updated to "gemini-2.5-pro"
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 829513627
Merge https://github.com/google/adk-python/pull/3127
# What this PR does
This PR fixes a bug in the `execute_sql function` within `bigquery/query_tool.py`. The bug caused an error when executing queries that do not return a result set, such as a `CREATE TEMP FUNCTION` statement.
# The problem
Within `execute_sql,` when a user executed a query that doesn't produce a result set, like the following:
```sql
CREATE TEMP FUNCTION f() AS (0); SELECT f();
```
The corresponding BigQuery job object would have its `destination` property set to `None`. This caused an error because the code was written with the expectation of a valid destination table.
# The solution
The fix modifies `execute_sql` to check if the `query_job.destination` is None. If it is, the function correctly identifies the query as a statement that doesn't require a destination and allows it to complete successfully.
This ensures that `execute_sql` can robustly handle these types of queries.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3127 from na0fu3y:patch-1 69218a8d25699dfa2e18bb305087f01192e91e91
PiperOrigin-RevId: 829270885
This change adds a debug log statement to output the function response IDs and the event list when a matching function call event is not found, which helps in debugging.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 829059186
Capture the function call ID from events and use it to populate the `function_response.id` in subsequent user messages, enabling recording and replaying of test cases involving long-running tools.
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 829042356
Add `_to_litellm_response_format` to convert ADK's `response_schema` types (Pydantic models, JSON schema dicts) into the format needed by LiteLLM for JSON object/schema constraints
Close#1967
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 829037987
In `gemini_llm_connection.py`, accumulate partial transcription texts and emit `LlmResponse` with `partial=True` for each chunk. When the transcription is marked as `finished`, emit a final `LlmResponse` with the full accumulated text and `partial=False`.
In `runners.py`, modify `_should_append_to_history` to only add transcription events to the history when they are fully finished, preventing partial transcriptions from being added.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 829029715
This is about 35% decrease. This change refactors several ADK modules to import `vertexai` and its submodules only when they are first used, rather than at the top of the file. This improves module load times by avoiding unnecessary imports of large dependencies. Imports are also placed within `if TYPE_CHECKING:` blocks where appropriate.
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 829017293
This accounts for about 8% of latency in cold start, because DatabaseSessionService imports from sqlalchemy. After the change, DatabaseSessionService is only imported if it's really needed by the program. The other objects in this file are not affected because they contribute to a small fraction of the latency.
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 829009868
Merge https://github.com/google/adk-python/pull/3324
**Problem:**
ADK seems to not pass output/input transcription `finished` flag from the Gemini.
**Solution:**
Relaxation of checking conditions of valid llm_response for input/output transcription.
### Testing Plan
Unit test `test_receive_transcript_finished` checks if input/output transcription message with no text but `finished` flag is received.
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
<img width="785" height="373" alt="image" src="https://github.com/user-attachments/assets/6d870e9f-1372-4808-91a9-38578c1b3729" />
**Manual End-to-End (E2E) Tests:**
Configure Gemini Agent to produce input & output transcriptions. Observe incoming transcript messages - to see if the finished flag appears at the end agents & users statement.
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
### Additional context
The mentioned `finished` flag can be obtained in native Gemini APIs like via Websocket but not via ADK.
Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3324 from ChrisQlasty:fix/transcript_finish e7b8e5e5f5fac1d2dfd495f2dbadb19ed4328b0c
PiperOrigin-RevId: 828987996
SaveFilesAsArtifactsPlugin now resolves the canonical URI for each saved artifact. When the URI is model-accessible (`gs://`, `https://`, `http://`), we add a `Part(file_data=...)` so the LLM can fetch the filedirectly while still emitting the placeholder. If no model-accessible URI exists, we retain the original inline blob alongside the placeholder to preserve access to the uploaded bytes.
Close#2016
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 828786519
The `_run_compaction_default` method is no longer called and can be safely removed.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 828760157
Merge https://github.com/google/adk-python/pull/3403
This PR corrects misspellings identified by the [check-spelling action](https://github.com/marketplace/actions/check-spelling)
Note: while I use tooling to identify errors, the tooling doesn't _actually_ provide the corrections, I'm picking them on my own. I'm a human, and I may make mistakes.
### Testing Plan
The misspellings have been reported at https://github.com/jsoref/adk-python/actions/runs/19056081305/attempts/1#summary-54426435973
The action reports that the changes in this PR would make it happy: https://github.com/jsoref/adk-python/actions/runs/19056081446/attempts/1#summary-54426436321
**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [ ] All unit tests pass locally.
_Please include a summary of passed `pytest` results._
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [ ] New and existing unit tests pass locally with my changes.
- [ ] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
### Additional context
- https://github.com/google/adk-python/pull/3382#issuecomment-3488654110
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3403 from jsoref:spelling-markdown 432b7ded3bddfe4a1d8127c50fd7a001f19bda83
PiperOrigin-RevId: 828754459
Merge https://github.com/google/adk-python/pull/2582
Relate to #3306
## Description
Fixes issues #6 and #1785 where ADK commands crash on Windows due to symlink creation requiring admin privileges.
## Problem
On Windows, running ADK commands (like `adk run`) fails with `OSError: [WinError 1314] A required privilege is not held by the client: ...` because the logging system attempts to create a symlink for the latest log file. Windows requires administrator privileges for symlink creation by default (unless Developer Mode is enabled), causing crashes for non-admin users.
## Root Cause
The issue was in [`logs.py`](https://github.com/google/adk-python/blob/main/src/google/adk/cli/utils/logs.py#L72) where `os.symlink()` was called unconditionally without error handling, causing the entire CLI to crash when symlink creation failed.
## Solution
This PR implements graceful symlink handling. Changes made:
- Extracted symlink creation into separate function with error handling
- Added graceful fallback when symlink creation fails
- Replaced crashes with warnings to keep CLI functional
- Improved user messaging about log file locations
This solution follows a similar pattern to the one used in [ROS2](https://github.com/ros2) in its [logging module](https://github.com/ros2/launch/blob/rolling/launch/launch/logging/__init__.py#L93).
## Testing
### Before (broken)
```bash
> adk run my_agent
Log setup complete: C:\Users\username\AppData\Local\Temp\agents_log\agent.20250817_215119.log
Traceback (most recent call last):
File "google\adk\cli\utils\logs.py", line 72, in log_to_tmp_folder
os.symlink(log_filepath, latest_log_link)
OSError: [WinError 1314] A required privilege is not held by the client
```
### After (fixed)
```bash
> adk run my_agent
Log setup complete: C:\Users\username\AppData\Local\Temp\agents_log\agent.20250817_215319.log
UserWarning: Cannot create symlink for latest log file: [WinError 1314] A required privilege is not held by the client
To access latest log: tail -F C:\Users\username\AppData\Local\Temp\agents_log\agent.20250817_215319.log
Running agent my_agent, type exit to exit.
```
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2582 from lorenzofavaro:fix/windows-symlink-permissions 1e99a6287994f1bfd9ac11550d3dc06205998df5
PiperOrigin-RevId: 828690483
Merge https://github.com/google/adk-python/pull/3382
This PR corrects misspellings identified by the [check-spelling action](https://github.com/marketplace/actions/check-spelling)
Note: while I use tooling to identify errors, the tooling doesn't _actually_ provide the corrections, I'm picking them on my own. I'm a human, and I may make mistakes.
### Testing Plan
The misspellings have been reported at https://github.com/jsoref/adk-python/actions/runs/19056081305/attempts/1#summary-54426435973
The action reports that the changes in this PR would make it happy: https://github.com/jsoref/adk-python/actions/runs/19056081446/attempts/1#summary-54426436321
**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [ ] All unit tests pass locally.
_Please include a summary of passed `pytest` results._
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [ ] New and existing unit tests pass locally with my changes.
- [ ] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
### Additional context
- follow-up to #2447
Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3382 from jsoref:spelling 3df5932e97391c437e1638d7163e5e3d5c52d5c3
PiperOrigin-RevId: 828686941
Merge https://github.com/google/adk-python/pull/3394
This PR corrects misspellings identified by the [check-spelling action](https://github.com/marketplace/actions/check-spelling)
Note: while I use tooling to identify errors, the tooling doesn't _actually_ provide the corrections, I'm picking them on my own. I'm a human, and I may make mistakes.
### Testing Plan
The misspellings have been reported at https://github.com/jsoref/adk-python/actions/runs/19056081305/attempts/1#summary-54426435973
The action reports that the changes in this PR would make it happy: https://github.com/jsoref/adk-python/actions/runs/19056081446/attempts/1#summary-54426436321
**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [ ] All unit tests pass locally.
_Please include a summary of passed `pytest` results._
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [ ] New and existing unit tests pass locally with my changes.
- [ ] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
### Additional context
- https://github.com/google/adk-python/pull/3382#issuecomment-3488654110
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3394 from jsoref:spelling-contributing c3d5e342c4350f7cae9f8f0c6638b176f2e30e80
PiperOrigin-RevId: 828659867
This commit refactors the `BigQueryAgentAnalyticsPlugin` to leverage the modern BigQuery Storage Write API, replacing the previous implementation that used the legacy `insert_rows_json` method (based on `tabledata.insertAll`).
**Key Changes:**
* **Switched to Storage Write API:** Event logs are now ingested using the `BigQueryWriteClient` from the `google-cloud-bigquery-storage` library.
* **Utilizes Default Stream:** We are using the `_default` stream for sending data, which is an efficient method for streaming in data without needing to manage stream lifecycles. This is ideal for continuous event logging.
* **Apache Arrow Format:** Log entries are converted to the Apache Arrow format using `pyarrow` before being sent. The BigQuery table schema is dynamically converted to an Arrow schema. This binary format is more efficient than JSON.
* **Updated Initialization:** The plugin now initializes both the standard `bigquery.Client` (for table management) and the `BigQueryWriteClient`.
* **Test Updates:** Unit tests in `test_bigquery_logging_plugin.py` have been comprehensively updated to mock the new `BigQueryWriteClient`, `bq_schema_utils`, and `pyarrow` components. Tests now verify calls to `append_rows` and the data structure passed to create the Arrow RecordBatch.
**Benefits of this change:**
* **Improved Performance:** The Storage Write API is designed for high-throughput streaming and offers better performance compared to the legacy API.
* **Reduced Cost:** Ingesting data via the Storage Write API is generally more cost-effective.
* **Enhanced Reliability:** The Storage Write API provides more robust streaming capabilities.
* **Modernization:** Aligns the plugin with the recommended best practices for BigQuery data ingestion.
This change enhances the efficiency and scalability of the BigQuery logging plugin.
PiperOrigin-RevId: 828655496
Merge https://github.com/google/adk-python/pull/3411
## Summary
Fixes AgentTool cleanup to prevent MCP session errors by calling `runner.close()` after sub-agent execution.
## Problem
When using AgentTool with MCP tools, the runner cleanup happened during garbage collection in a different async task context, causing:
```
RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
```
## Solution
- Call `await runner.close()` immediately after sub-agent execution in AgentTool
- This ensures MCP sessions and other resources are cleaned up in the correct async task context
- Updated test mock to include the close() method
## Demo Agents
Added two comprehensive demo agents showing how to use AgentTool with MCP tools:
### mcp_in_agent_tool_remote (SSE mode)
- Uses HTTP/SSE connection to remote MCP server
- Zero-installation setup with `uvx`
- Demonstrates server-side MCP deployment pattern
### mcp_in_agent_tool_stdio (stdio mode)
- Uses subprocess connection with automatic server launch
- Fully automatic setup with `uvx` subdirectory syntax
- Demonstrates embedded MCP deployment pattern
Both demos:
- Use Gemini 2.5 Flash
- Include example prompts for JSON Schema exploration
- Have comprehensive READMEs with architecture diagrams
- Follow ADK agent structure conventions
## Testing
- ✅ All existing unit tests pass
- ✅ Manual testing with both SSE and stdio modes
- ✅ Verified cleanup happens in correct async context
- ✅ No more cancel scope errors with MCP tools
## Related
- Fixes#1112
- Related to #929
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3411 from google:fix/agent-tool-mcp-cleanup 9ae753b5a4
PiperOrigin-RevId: 828651896
Currently ADK web hangs and logs "AGSI callable returned without completing response" when the server is unreachable. To fix, set timeouts for connecting to server.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 828648928
- add FileArtifactService that persists artifacts to the local filesystem
- adjust BaseArtifactService and exports so callers can wire in the filebacked implementation
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 828629298
Replace the full JSON schema dump with a compact text summary of key AgentConfig components like LlmAgent, ToolConfig, and GenerateContentConfig
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 828627911
Merge https://github.com/google/adk-python/pull/3407
This PR corrects misspellings identified by the [check-spelling action](https://github.com/marketplace/actions/check-spelling)
Note: while I use tooling to identify errors, the tooling doesn't _actually_ provide the corrections, I'm picking them on my own. I'm a human, and I may make mistakes.
### Testing Plan
The misspellings have been reported at https://github.com/jsoref/adk-python/actions/runs/19056081305/attempts/1#summary-54426435973
The action reports that the changes in this PR would make it happy: https://github.com/jsoref/adk-python/actions/runs/19056081446/attempts/1#summary-54426436321
**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [ ] All unit tests pass locally.
_Please include a summary of passed `pytest` results._
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [ ] New and existing unit tests pass locally with my changes.
- [ ] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
### Additional context
- https://github.com/google/adk-python/pull/3382#issuecomment-3488654110
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3407 from jsoref:spelling-issue-template ce8febc6ab5368640c0ec2ae5d6a2c8ac5bf8ed6
PiperOrigin-RevId: 828610865
The blob content is often large and binary, which makes the logs unreadable and can cause excessive logging.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 828523413
The sample agent now uses updated model names for Gemini Live, including a new Vertex model as the default and a new AI Studio model option.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 828515811
Merge https://github.com/google/adk-python/pull/3381
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #3363
- This PR sets a max column width for the table printed in detailed output of agent evaluations.
**Problem:**
The detailed output of agent evaluations is not readable due to rows in the table getting wrapped. This happens when there are long text values in cells.
<img width="1904" height="717" alt="508807185-9e8fe1c3-d04a-43dd-acf9-0befaa1b247d" src="https://github.com/user-attachments/assets/61526ad2-8a9e-4c18-83e2-51a3b9b32d2b" />
**Solution:**
Existing code uses `tabulate` python package to format the table. We can set a maximum column width using `maxcolwidths` parameter. I have set it to `25`.
After the fix:
<img width="1882" height="711" alt="508810179-b91c5bca-fb43-480b-90ff-bca2e909417c" src="https://github.com/user-attachments/assets/b653f825-719e-4101-9acb-e28a52694cf8" />
### Testing Plan
I have manually tested if the output is properly displayed after changes. Please let me know if any unit tests can be added for this.
**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
<img width="1627" height="39" alt="image" src="https://github.com/user-attachments/assets/59a70619-3669-4113-8ab7-dcff130ee241" />
**Manual End-to-End (E2E) Tests:**
1. Create a simple agent using adk (preferably an agent that outputs a long text).
2. Create an evalset for this agent.
3. Run the evalset with `print_detailed_results` option and check if the output is properly displayed.
If you want a quick setup for testing this, I have a sample repo with an agent and an evalset [here](https://github.com/nimanthadilz/adk-test/tree/reproduce-print-detailed-results). You will have to manually build & install the fixed adk version to test it.
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3381 from nimanthadilz:fix-eval-output-rows-wrapping-issue f6d40121f621df60c4596a1c62e0c54e4da309d3
PiperOrigin-RevId: 828265715
Merge https://github.com/google/adk-python/pull/2651
### Summary
Correct a misspelling in the build configuration:
- "swtich" → "switch" in `pyproject.toml`.
### Rationale
This is a spelling fix only. It improves readability and avoids potential confusion in configuration.
There is no impact on runtime behavior, tests, or public APIs.
### Notes
- Follows Conventional Commits style for build/config changes (`build:`).
- CLA status should be green via the Google CLA bot.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2651 from marsboy02:docs/fix-type-pyproject b78c014c864b1a143ffc157c7a8c807f5f19d31d
PiperOrigin-RevId: 828221776
This change introduces BigQueryLoggerConfig to allow customization of the BigQueryAgentAnalyticsPlugin. Users can now enable/disable the plugin, specify event type allowlists and denylists, and provide a custom function to format or redact the content field before logging to BigQuery. The content logged for model and tool errors has also been enhanced.
PiperOrigin-RevId: 828172241
Add support for MCP prompts via the McpInstructionProvider class, which can be specified as an agent's instruction.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 828166051
Users were getting spammed with this log even though their tools didn't require authentication. To fix, reduce the log level to DEBUG so that it doesn't show up by default.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 828161281
This change introduces a new section in the README.md to highlight the `adk-python-community` GitHub repository, describing it as a place for community-contributed tools and integrations.
Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 828155205
Populate the usage_metadata field for live events with the metadata provided by the Gemini live API.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 828124232
This lets users to specify `drop_params` when initializing `LiteLlm`, which will be forwarded to LiteLLM's `acompletion` or `completion` calls
Close#1718
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 828058105
LiteLLM providers can extract the MIME type from the data URI. Removing the separate `format` field avoids redundancy and potential issues with backends that may reject requests containing this field.
Close#2017
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 828014286
ARIMA supports both historical data and future data anomaly detection. This CL add how the tool support future table anomaly detection.
PiperOrigin-RevId: 827803748
Merge https://github.com/google/adk-python/pull/3365
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
fix typo for several files.
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
### Additional context
_Add any other context or screenshots about the feature request here._
Co-authored-by: Liang Wu <wuliang@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3365 from UlookEE:fix_typo 1469de4ea354d1c205268b999183ee86c9d6a1d5
PiperOrigin-RevId: 827724001
Merge #3163
END_PUBLIC
Hello,
Since global_instruction has been deprecated, I’m migrating to GlobalInstructionPlugin.
During the migration, I encountered an error and am submitting this PR to fix it.
In [df05ed6](https://github.com/google/adk-python/commit/df05ed6b3b7b218d85fddc1acd6617802cdf6f2a) ,
GlobalInstructionPlugin references invocation_context, but CallbackContext actually contains _invocation_context.
This mismatch always causes an error during execution.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3180 from UlookEE:fix_global_instruction_plugin e289a12d69812f0abcfe77db0114fdb2045b31bc
PiperOrigin-RevId: 827682501
Merge https://github.com/google/adk-python/pull/2326
`adk run --help` (adk 1.9.0)
```
--resume FILE The json file that contains a previously saved session
(by--save_session option). The previous session will be
re-displayed. And user can continue to interact with the
agent.
```
## testing plan
N/A (because this is a simple string correction)
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2326 from ftnext:fix-typo-run-help-resume a896fa38e223b13e7edd8125d7b38139f1ca3712
PiperOrigin-RevId: 827311506
This fixes MCP authentication for gcloud service accounts. Previously it was failing to authenticate tool calls.
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 826639044
Merge https://github.com/google/adk-python/pull/3345
Add run_debug() helper method to InMemoryRunner that reduces agent execution boilerplate from 7-8 lines to just 2 lines, making it ideal for quick experimentation, notebooks, and getting started with ADK.
**Key changes:**
• Introduce run_debug() to reduce boilerplate from 7-8 lines to 2 lines
• Enable quick testing in notebooks, REPL, and during development
• Support single or multiple messages with automatic session management
• Add verbose flag to show/hide tool calls and intermediate processing
• Add quiet flag to suppress console output while capturing events
• Extract event printing logic to reusable utility (utils/_debug_output.py)
• Include comprehensive test suite with 21 test cases covering all part types
• Provide complete working example with 8 usage patterns
• **This is a convenience method for experimentation, not a replacement for run_async()**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
* N/A - New feature to improve developer experience
**2. Or, if no issue exists, describe the change:**
**Problem:**
Developers need to write 7-8 lines of boilerplate code just to test a simple agent interaction during development. This creates friction for:
* New developers getting started with ADK
* Quick experimentation in Jupyter notebooks or Python REPL
* Debugging agent behavior during development
* Writing examples and tutorials
* Rapid prototyping of agent capabilities
**Solution:**
Introduce `run_debug()` as a convenience helper method specifically designed for quick experimentation and getting started scenarios. This method:
* **Is NOT a replacement for `run_async()`** - it's a developer convenience tool
* **Reduces boilerplate** from 7-8 lines to just 2 lines for simple testing
* **Handles session management automatically** with sensible defaults
* **Provides debugging visibility** with optional verbose flag for tool calls
* **Supports common patterns** like multiple messages and event capture
* **Type-safe implementation** using direct attribute access instead of getattr()
### Before vs After Comparison
**BEFORE - Current approach requires 7-8 lines of boilerplate:**
```python
from google.adk import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
# Define a simple agent
agent = Agent(
model="gemini-2.5-flash",
instruction="You are a helpful assistant"
)
# Need all this boilerplate just to test the agent
APP_NAME = "default"
USER_ID = "default"
session_service = InMemorySessionService()
runner = Runner(agent=agent, app_name=APP_NAME, session_service=session_service)
session = await session_service.create_session(
app_name=APP_NAME, user_id=USER_ID, session_id="default"
)
content = types.Content(role="user", parts=[types.Part.from_text("Hello")])
async for event in runner.run_async(
user_id=USER_ID, session_id=session.id, new_message=content
):
if event.content and event.content.parts:
print(event.content.parts[0].text)
```
**AFTER - With run_debug() helper, just 2 lines:**
```python
from google.adk import Agent
from google.adk.runners import InMemoryRunner
# Define the same agent
agent = Agent(
model="gemini-2.5-flash",
instruction="You are a helpful assistant"
)
# Test it with just 2 lines!
runner = InMemoryRunner(agent=agent)
await runner.run_debug("Hello")
```
### API Design
```python
async def run_debug(
self,
user_messages: str | list[str],
*,
user_id: str = 'debug_user_id',
session_id: str = 'debug_session_id',
run_config: RunConfig | None = None,
quiet: bool = False,
verbose: bool = False,
) -> list[Event]:
```
**Parameters:**
* `user_messages`: Single message string or list of messages (required)
* `user_id`: User identifier (default: 'debug_user_id')
* `session_id`: Session identifier for conversation continuity (default: 'debug_session_id')
* `run_config`: Optional advanced configuration
* `quiet`: Suppress console output (default: False)
* `verbose`: Show detailed tool calls and responses (default: False)
**Key Features:**
* **Always returns events** - Simplifies API, no conditional return type
* **Type-safe implementation** - Uses direct attribute access on Pydantic models
* **Text buffering** - Consecutive text parts printed without repeated author prefix
* **Smart truncation** - Long tool args/responses truncated for readability
* **Clean session management** - Get-then-create pattern, no try/except
* **Reusable printing logic** - Extracted to utils/_debug_output.py for other tools
### Implementation Highlights
**1. Event Printing Utility (utils/_debug_output.py):**
* Modular print_event() function for displaying events
* Text buffering to combine consecutive text parts
* Configurable truncation for different content types:
- Function args: 50 chars max
- Function responses: 100 chars max
- Code output: 100 chars max
* Supports all ADK part types (text, function_call, executable_code, inline_data, file_data)
**2. Session Management:**
```python
# Clean get-then-create pattern (no try/except)
session = await self.session_service.get_session(
app_name=self.app_name, user_id=user_id, session_id=session_id
)
if not session:
session = await self.session_service.create_session(
app_name=self.app_name, user_id=user_id, session_id=session_id
)
```
**3. Type-Safe Event Processing:**
* Direct attribute access on Pydantic models (no getattr() or hasattr())
* Proper handling of all part types
* Leverages `from __future__ import annotations` for duck typing
### Important Note on Scope
`run_debug()` is a **convenience method for experimentation only**. For production applications requiring:
* Custom session services (Spanner, Cloud SQL)
* Fine-grained event processing control
* Error recovery and resumability
* Performance optimization
* Complex authentication flows
Continue using the standard `run_async()` method. The `run_debug()` helper is specifically designed to lower the barrier to entry and speed up the development/testing cycle.
### Testing Plan
**Unit Tests (21 test cases in tests/unittests/runners/test_runner_debug.py):**
**Core functionality (7 tests):**
* ✅ Single message execution and event return
* ✅ Multiple messages in sequence
* ✅ Quiet mode (suppresses output)
* ✅ Custom session_id configuration
* ✅ Custom user_id configuration
* ✅ RunConfig passthrough
* ✅ Session persistence across calls
**Part type handling (8 tests):**
* ✅ Tool calls and responses (verbose mode)
* ✅ Executable code parts
* ✅ Code execution result parts
* ✅ Inline data (images)
* ✅ File data references
* ✅ Mixed part types in single event
* ✅ Long output truncation
* ✅ Verbose flag behavior (show/hide tools)
**Edge cases (6 tests):**
* ✅ None text filtering
* ✅ Existing session handling
* ✅ Empty parts list
* ✅ None event content
* ✅ Verbose=False hides tool calls
* ✅ Verbose=True shows tool calls
**All 21 tests passing in 3.8s** ✓
**Manual End-to-End (E2E) Tests:**
Tested all 8 example patterns in contributing/samples/runner_debug_example/main.py:
1. ✅ Minimal 2-line usage
2. ✅ Multiple sequential messages
3. ✅ Session persistence across calls
4. ✅ Multiple user sessions (Alice & Bob)
5. ✅ Verbose mode for tool visibility
6. ✅ Event capture with quiet mode
7. ✅ Custom RunConfig integration
8. ✅ Before/after comparison
### Files Changed
**Core implementation:**
* src/google/adk/runners.py - Added run_debug() method (~60 lines)
* src/google/adk/utils/_debug_output.py - Event printing utility (~106 lines)
**Tests:**
* tests/unittests/runners/test_runner_debug.py - Comprehensive test suite (21 tests)
**Examples:**
* contributing/samples/runner_debug_example/agent.py - Sample agent with tools
* contributing/samples/runner_debug_example/main.py - 8 usage examples
* contributing/samples/runner_debug_example/README.md - Complete documentation
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have added tests that prove my fix is effective or that my feature works
- [x] New and existing unit tests pass locally with my changes (21/21 passing)
- [x] I have manually tested my changes end-to-end (8 examples tested)
- [x] Code follows ADK style guide (relative imports, type hints, 2-space indentation)
- [x] Ran ./autoformat.sh before committing
- [x] Any dependent changes have been merged and published in downstream modules
### Additional Context
**Example with Tools (verbose mode):**
```python
# Create agent with tools
agent = Agent(
model="gemini-2.5-flash",
instruction="You can check weather and do calculations",
tools=[get_weather, calculate]
)
# Test with verbose to see tool calls
runner = InMemoryRunner(agent=agent)
await runner.run_debug("What's the weather in SF?", verbose=True)
# Output:
# User > What's the weather in SF?
# agent > [Calling tool: get_weather({'city': 'San Francisco'})]
# agent > [Tool result: {'result': 'Foggy, 15°C (59°F)'}]
# agent > The weather in San Francisco is foggy, 15°C (59°F).
```
**Complete Example Included:**
The PR includes a full working example in `contributing/samples/runner_debug_example/` with:
* Agent with weather and calculator tools
* 8 different usage patterns
* Comprehensive README with troubleshooting
* Safe AST-based expression evaluation
**Breaking Changes:** None - this is purely additive.
**Security:** Example uses AST-based expression evaluation instead of eval().
**Code Quality:**
* Type-safe implementation (no getattr() or hasattr())
* Modular design (printing logic separated into utility)
* Follows ADK conventions (relative imports, from __future__ import annotations)
* Comprehensive error handling (gracefully handles None content, empty parts)
* Well-documented with docstrings and inline comments
END_PUBLIC
```
---
## Key Changes from Original:
1. ✅ Updated parameter name: `user_queries` → `user_messages`
2. ✅ Updated parameter name: `session_name` → `session_id`
3. ✅ Updated parameter name: `print_output` → `quiet`
4. ✅ Removed `return_events` parameter
5. ✅ Updated test count: 23 → 21
6. ✅ Changed "queries" → "messages" throughout
7. ✅ Added implementation highlights section
8. ✅ Added details about utils/_debug_output.py
9. ✅ Updated default values to debug_user_id/debug_session_id
10. ✅ Noted type-safe implementation
11. ✅ Added Code Quality section
12. ✅ Updated API signature to match final refactored version
13. ✅ Removed optional return type (always returns list[Event])
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3345 from lavinigam-gcp:adk-runner-helper e0050b9f152d0f0e49e6501610d2c59a754fc571
PiperOrigin-RevId: 826607817
Removes the dataset_id field from the BigQuery table schema and from each log entry created by the BigQueryAgentAnalyticsPlugin. This field is redundant, as all rows logged to a specific table belong to the same dataset.
To ensure the plugin can still target the correct dataset, dataset_id is now a required argument in the BigQueryAgentAnalyticsPlugin constructor, and its default value has been removed.
The BigQuery client user_agent is also updated with plugin version info to help identify traffic originating from this plugin. Unit tests have been updated to reflect the removal of dataset_id from log entries.
PiperOrigin-RevId: 826596499
This change adds an optional `runner` parameter to the `to_a2a` function, enabling users to provide a pre-configured `Runner` instance instead of always using the default in-memory services. A new test case has been added to verify this functionality.
closes#3104
Co-authored-by: Dongyu Jia <dongyuj@google.com>
PiperOrigin-RevId: 826526861
This change introduces a sample (`migration_session_db`) demonstrating how to load a session database created with an older version of ADK (e.g., 1.15.0) and make it compatible with the current version. It includes a script (`db_migration.sh`) to alter the SQLite schema automatically. to_event is updated to handle potential discrepancies in pickled `EventActions` by using `model_copy` to ensure compatibility with the latest `EventActions` model definition.
Related to #3272#3197, Closes#3197#3272
Co-authored-by: Dongyu Jia <dongyuj@google.com>
PiperOrigin-RevId: 826524368
It is common for expected response and expected tool calls column to be empty for user simulated conversations. So, we don't render those.
Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 826202867
Previously we only do a simple prefix string matching, thus `agent_00` will match with `agent_0`
With this new change, we either check directly equality, or must expect seeing `agent_0.`. See added test for branches we now match / skip.
TBF `.` is also not a perfect delimiter (I would imagine users might put dot in agent names). We might consider a follow up that bans such agent names.
Tested with script in the linked issue (I updated prompt so we see which agent they see from):
Before:
```
[agent_8]: 73
[agent_0]: 97
[agent_1]: 73
[agent_5]: 97
[agent_4]: 73
[agent_2]: 73
[agent_3]: 73
[agent_9]: 93
[agent_6]: 73
[agent_7]: 1
[agent_70]: 1 (agent_7)
[agent_20]: 73 (agent_2)
[agent_30]: 73 (agent_3)
[agent_00]: 97 (agent_0)
[agent_40]: 73 (agent_4)
[agent_80]: 73 (agent_8)
[agent_50]: 97 (agent_5)
[agent_90]: 93 (agent_9)
[agent_10]: 73 (agent_1)
[agent_60]: 73 (agent_6)
```
After:
```
[agent_9]: 73
[agent_6]: 73
[agent_2]: 73
[agent_7]: 93
[agent_4]: 73
[agent_1]: 73
[agent_3]: 73
[agent_5]: 97
[agent_0]: 73
[agent_8]: 87
[agent_50]: 0
[agent_80]: 0
[agent_10]: 0
[agent_90]: 0
[agent_30]: 0
[agent_20]: 0
[agent_60]: 0
[agent_00]: 0
[agent_40]: 0
[agent_70]: 0
```
Closes#2948
Co-authored-by: Kevin Qian <kqian@google.com>
PiperOrigin-RevId: 826187198
Merge https://github.com/google/adk-python/pull/3219
## Summary
Enhance error messages for tool and agent not found errors to provide actionable guidance and reduce developer debugging time from hours to minutes.
Fixes#3217
## Changes
### Modified Files
1. **`src/google/adk/flows/llm_flows/functions.py`**
- Enhanced `_get_tool()` error message with:
- Available tools list (formatted, truncated to 20 for readability)
- Possible causes
- Suggested fixes
- Fuzzy matching suggestions
2. **`src/google/adk/agents/llm_agent.py`**
- Enhanced `__get_agent_to_run()` error message with:
- Available agents list (formatted, truncated to 20 for readability)
- Timing/ordering issue explanation
- Fuzzy matching for agent names
- Added `_get_available_agent_names()` helper method
### New Test Files
3. **`tests/unittests/flows/llm_flows/test_functions_error_messages.py`**
- Tests for enhanced tool not found error messages
- Fuzzy matching validation
- Edge cases (no close matches, empty tools dict, 100+ tools)
4. **`tests/unittests/agents/test_llm_agent_error_messages.py`**
- Tests for enhanced agent not found error messages
- Agent tree traversal validation
- Fuzzy matching for agents
- Long list truncation
## Testing Plan
### Unit Tests
```bash
pytest tests/unittests/flows/llm_flows/test_functions_error_messages.py -v
pytest tests/unittests/agents/test_llm_agent_error_messages.py -v
```
**Results**: ✅ 8/8 tests passing
```
tests/unittests/flows/llm_flows/test_functions_error_messages.py::test_tool_not_found_enhanced_error PASSED
tests/unittests/flows/llm_flows/test_functions_error_messages.py::test_tool_not_found_fuzzy_matching PASSED
tests/unittests/flows/llm_flows/test_functions_error_messages.py::test_tool_not_found_no_fuzzy_match PASSED
tests/unittests/flows/llm_flows/test_functions_error_messages.py::test_tool_not_found_truncates_long_list PASSED
tests/unittests/agents/test_llm_agent_error_messages.py::test_agent_not_found_enhanced_error PASSED
tests/unittests/agents/test_llm_agent_error_messages.py::test_agent_not_found_fuzzy_matching PASSED
tests/unittests/agents/test_llm_agent_error_messages.py::test_agent_tree_traversal PASSED
tests/unittests/agents/test_llm_agent_error_messages.py::test_agent_not_found_truncates_long_list PASSED
8 passed, 1 warning in 4.38s
```
### Example Enhanced Error Messages
#### Before (Current Error)
```
ValueError: Function get_equipment_specs is not found in the tools_dict: dict_keys(['get_equipment_details', 'query_vendor_catalog', 'score_proposals'])
```
#### After (Enhanced Error)
```
Function 'get_equipment_specs' is not found in available tools.
Available tools: get_equipment_details, query_vendor_catalog, score_proposals
Possible causes:
1. LLM hallucinated the function name - review agent instruction clarity
2. Tool not registered - verify agent.tools list
3. Name mismatch - check for typos
Suggested fixes:
- Review agent instruction to ensure tool usage is clear
- Verify tool is included in agent.tools list
- Check for typos in function name
Did you mean one of these?
- get_equipment_details
```
## Community Impact
- **Addresses 3 active issues**: #2050, #2933 (12 comments), #2164
- **Reduces debugging time** from 3+ hours to < 5 minutes (validated in production multi-agent RFQ solution for recent partner nanothon initiative)
- **Improves developer experience** for new ADK users
## Implementation Details
- Uses standard library `difflib` for fuzzy matching (no new dependencies)
- Error path only (no performance impact on happy path)
- Measured performance: < 0.03ms per error
- Truncates long lists to first 20 items to prevent log overflow
- Fully backward compatible (same exception types)
## Checklist
- [x] Unit tests added and passing (8/8 tests)
- [x] Code formatted with `./autoformat.sh` (isort + pyink)
- [x] No new dependencies (uses standard library `difflib`)
- [x] Docstrings updated
- [x] Tested with Python 3.11
- [x] Issue #3217 created and linked
## Related Issues
- Fixes#3217
- Addresses #2050 - Tool verification callback request
- Addresses #2933 - How to handle "Function is not found in the tools_dict" Error
- Addresses #2164 - ValueError: {agent} not found in agent tree
---
**Note**: For production scenarios where LLM tool hallucinations occur, ADK's built-in [`ReflectAndRetryToolPlugin`](https://github.com/google/adk-python/blob/main/src/google/adk/plugins/reflect_retry_tool_plugin.py) can automatically retry failed tool calls (available since v1.16.0). This PR's enhanced error messages complement that by helping developers quickly identify and fix configuration issues during development.
Cheers, JP
Co-authored-by: Yvonne Yu <yyyu@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3219 from jpantsjoha:feat/better-error-messages a4df8bfb031685dce9e528d8eb7006f53447b75b
PiperOrigin-RevId: 826132579
Make sure _add_instructions_to_user_content skips over user messages that carry function_response parts so tool_use/tool_result blocks stay together
Close#3229
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 826076141
Include a manual mode for testing first and will remove after verifying it works.
When a commit with `Merge https://github.com/google/adk-python/pull/3333` in description is pushed by copybara, the workflow will automatically close the PR.
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 826058313
Remove validation for output_schema and agent transfer flags.
The check that prevented `output_schema` from co-existing with agent transfer capabilities (`disallow_transfer_to_parent` or `disallow_transfer_to_peers` being False) has been removed. The agent will no longer automatically set these transfer flags to True when `output_schema` is present.
Co-authored-by: Ieva Grublyte <ievagrublyte@google.com>
PiperOrigin-RevId: 825998224
Merge https://github.com/google/adk-python/pull/3282
The `process_bind_param` and `process_result_value` methods in the `DynamicPickleType` class have been modified to handle MySQL dialect in addition to Spanner. This change ensures that pickled values are correctly processed for both database types.
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #3283
**2. Or, if no issue exists, describe the change:**
_If applicable, please follow the issue templates to provide as much detail as
possible._
**Problem:**
When using `DatabaseSessionService` with MySQL backend in google-adk v1.17.0, the application crashes with the following error: app.resources.runner:event_generator:260 - Error in event_generator: (builtins.TypeError) 'tuple' object cannot be interpreted as an integer
<img width="1237" height="129" alt="image" src="https://github.com/user-attachments/assets/0a5fc223-600a-4a92-8443-4d37fb1267f6" />
Root cause: The `DynamicPickleType` class in `database_session_service.py` configures MySQL dialect to use `LONGBLOB` for storing pickled data (line 117-118), but the `process_bind_param` and `process_result_value` methods only handle pickle serialization/deserialization for Spanner dialect, not MySQL. This causes MySQL to attempt storing raw Python objects instead of pickled bytes, leading to serialization errors and potential data corruption.
**Solution:**
Added MySQL to the pickle serialization logic in both `process_bind_param` and `process_result_value` methods, treating it the same way as Spanner dialect. This ensures that:
- Data is properly pickled to bytes before being stored in MySQL's LONGBLOB column
- Data is properly unpickled when retrieved from the database
- No breaking changes to existing functionality for other dialects (SQLite, PostgreSQL)
### Testing Plan
_Please describe the tests that you ran to verify your changes. This is required
for all PRs that are not small documentation or typo fixes._
**Unit Tests:**
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
**Summary of `pytest` results:**
<img width="929" height="306" alt="image" src="https://github.com/user-attachments/assets/3d548b96-ac49-4101-8405-a289a722293c" />
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
### Checklist
- [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
### Additional context
_Add any other context or screenshots about the feature request here._
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3282 from hung12ct:fix/mysql-pickle-serialization d9df37adb7dfbbfd8502a0fe65c4f8bca3d0d978
PiperOrigin-RevId: 825834360
This CL introduces a new tool, get_job_info, to the BigQuery toolset. This tool allows retrieving metadata about a BigQuery job, such as slot usage, job configuration, statistics, and job status.
Closes#2928
Co-authored-by: Dongyu Jia <dongyuj@google.com>
PiperOrigin-RevId: 825762399
Session input file contains fields that are needed to run evals and later be able retrieve the session generated by them.
Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 825742522
We also change VertexAiSessionService and VertexAiMemoryBankService to both use keyword arguments for project, location, agent engine id, and express mode api key
PiperOrigin-RevId: 825719331
Merge https://github.com/google/adk-python/pull/3333
## Summary
Add ignore patterns for popular AI coding assistant configuration files to prevent committing developer-specific settings. This aligns with the project's approach of providing `AGENTS.md` as a general starting point that developers can symlink or copy and customize locally.
## Changes
Added `.gitignore` patterns for 10 popular AI coding tools:
- **Claude Code** - `.claude/`, `CLAUDE.md`
- **Cursor** - `.cursor/`, `.cursorrules`, `.cursorignore`
- **Windsurf** - `.windsurfrules`
- **Aider** - `.aider*`
- **Continue.dev** - `.continue/`
- **Codeium** - `.codeium/`
- **GitHub Next** - `.githubnext/`
- **Roo Code** - `.roo/`, `.rooignore`
- **Bolt** - `.bolt/`
- **v0** - `.v0/`
## Rationale
Each developer may want different AI tool configurations and personal instructions. By ignoring these files, we:
- Prevent accidental commits of personal AI assistant settings
- Keep the repository clean of developer-specific configurations
- Allow developers to customize their AI tools without affecting others
- Maintain consistency with the project's `AGENTS.md` approach
Co-authored-by: Yvonne Yu <yyyu@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3333 from google:chore/ignore-ai-tool-configs 0abe4ccdf130ac93c3d2c353556f0ce7c305c429
PiperOrigin-RevId: 825682646
Usage: you can create symlink to AGENTS.md with the file name required by the specific AI coding tool.
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 825627185
Previously this will return true for events yielded from before_agent_callback when there are state changes.
Note with this change, it will also return false for state delta only callbacks even after main response, but this is fine as long as the actual final response event has it to be true.
Closes#2992
PiperOrigin-RevId: 825313208
Previously this will return true for events yielded from before_agent_callback when there are state changes.
Note with this change, it will also return false for state delta only callbacks even after main response, but this is fine as long as the actual final response event has it to be true.
Closes#2992
PiperOrigin-RevId: 825279439
Merge https://github.com/google/adk-python/pull/3037
fix: [#3036](https://github.com/google/adk-python/issues/3036)
- Fix FunctionTool parameter filtering to support CrewAI-style tools
- Functions with **kwargs now receive all parameters except 'self' and 'tool_context'
- Maintains backward compatibility with explicit parameter functions
- Add comprehensive tests for **kwargs functionality
Fixes parameter filtering issue where CrewAI tools using **kwargs pattern would receive empty parameter dictionaries, causing search_query and other parameters to be None.
#non-breaking
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3037 from omarcevi:fix/function-tool-kwargs-parameter-filtering 012bbfcfd68e83a29635ac74718a1bd1323c5187
PiperOrigin-RevId: 825275686
This change introduces a powerful pattern for customizing code execution environments by extending a base `CodeExecutor`. It showcases how to inject setup code to prepare the environment before a user's code is run, enabling advanced use cases that require specific configurations.
As a practical example, this change implements `CustomCodeExecutor`, a subclass of `VertexAiCodeExecutor`, to solve the problem of rendering non-standard characters in `matplotlib` plots (Issue #2993). The custom executor programmatically adds a Japanese font to the `matplotlib` font manager at runtime.
This is achieved by overriding the `execute_code` method to add font files to execution input and prepend the necessary font-loading logic. This approach is not limited to fonts and can be adapted for other setup tasks.
Fixes: #2993
PiperOrigin-RevId: 825240143
This change introduces a new sample agent and documentation to demonstrate the usage of the `VertexAiCodeExecutor`.
The new agent, located at `vertex_code_execution/agent.py`, is a direct counterpart to the existing sample at `code_execution/agent.py`. The key difference is that this new agent uses `VertexAiCodeExecutor` to execute code within the Vertex AI Code Interpreter Extension, whereas the original sample uses `BuiltInCodeExecutor` to run code in the model's built-in sandbox.
A `README.md` file is also included to provide an overview, setup instructions, and sample usage for the new agent.
Related: #2993
PiperOrigin-RevId: 825239758
This change introduces a new `detect_anomalies` tool in `query_tool.py` which uses BigQuery ML's `CREATE MODEL` with `ARIMA_PLUS` type and `ML.DETECT_ANOMALIES` to detect anomalies. The new function is also added to the `bigquery_toolset`.
PiperOrigin-RevId: 825181489
* feat: Added support for enums as arguments for function tools
* feat: Add default value support for function tools
fix: Add more test cases inside `test_build_function_declaration.py` for passing Enums as arguments
* fix: format code with pyink
---------
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
Co-authored-by: Yvonne Yu <150068659+yyyu-google@users.noreply.github.com>
ADK already has a set of metrics that don't rely expected_invocations. Also, for eval cases with conversation scenario, this would be the main line case.
PiperOrigin-RevId: 825101481
Introduces the `BigQueryLoggingPlugin` for capturing and sending ADK lifecycle events to Google BigQuery. This allows for persistent storage and analysis of agent and tool interactions. The plugin supports asynchronous logging, automatic dataset/table creation, and comprehensive event capture.
Also refactors common formatting utilities (_format_content, _format_args) for shared use.
PiperOrigin-RevId: 824703739
This CL refactors VertexAiSessionService to use the asynchronous aio client for all Vertex AI API calls. This ensures that the service methods are non-blocking and can be used effectively in an asyncio environment.
PiperOrigin-RevId: 824573356
The computer_use sample now supports launching with a `user_data_dir` to maintain browser state across runs. The sample agent is updated to use a shared temporary directory for the browser profile, preserving login sessions and other data.
PiperOrigin-RevId: 823749082
While testing the bidi streaming sample agent, I noticed that the import was erroring and I think it's a typo -- the other bidi sample agents all import `from google.adk.agents.llm_agent`.
PiperOrigin-RevId: 823662586
Details:
- Adds the `LlmBackedUserSimulator` which uses an LLM to generate user prompts until it decides that the conversation is complete.
- Adds unit tests for the new functionality.
PiperOrigin-RevId: 823557910
This change adds a new section to the README.md, detailing past community events. The first entry is for the completed ADK's 1st community meeting, with links to the recording and deck.
PiperOrigin-RevId: 823322924
Right now the failure eats up the traceback information and there is no clear way for the developer to know what went wrong. Adding this traceback info could give them the needed debugging information.
PiperOrigin-RevId: 823179833
## What's Added
- **PostgreSQL MCP Agent** ([mcp_postgres_agent/agent.py](cci:7://file:///Users/admin/git%20repos/adk-python/contributing/samples/mcp_postgres_agent/agent.py:0:0-0:0)): A fully functional agent that connects to PostgreSQL databases via the `postgres-mcp` MCP server
- **Comprehensive README** ([mcp_postgres_agent/README.md](cci:7://file:///Users/admin/git%20repos/adk-python/contributing/samples/mcp_postgres_agent/README.md:0:0-0:0)): Documentation with setup instructions, configuration details, and example queries
- **Environment Configuration**: Support for secure credential management via `.env` files
## Key Features
- **MCP Integration**: Demonstrates proper use of `MCPToolset` with `StdioConnectionParams`
- **Zero Installation**: Uses `uvx` to run the MCP server without manual installation
- **Secure Credentials**: Database connection strings passed via environment variables
- **Production-Ready**: Uses Gemini 2.0 Flash with unrestricted access mode for full database operations
## Technical Details
- **Model**: Gemini 2.0 Flash
- **MCP Server**: `postgres-mcp` (via `uvx`)
- **Connection**: StdioConnectionParams with 60-second timeout
- **Environment Variable**: Maps `POSTGRES_CONNECTION_STRING` to `DATABASE_URI`
## Testing
The agent has been tested with:
- PostgreSQL database connections (local and remote)
- Schema inspection queries
- Data querying operations
- Table listing and management
## Example Queries
Users can interact with the agent using natural language queries like:
- "What tables are in the database?"
- "Show me the schema for the users table"
- "Query the first 10 rows from the products table"
This sample serves as a reference implementation for developers looking to integrate PostgreSQL databases with ADK agents using MCP.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3182 from Vrajesh-Babu:postgres-mcp f3b3846abae37ae376d3554624ac2b1be82f7adc
PiperOrigin-RevId: 822865931
The "What's new" section has been updated to highlight: Custom API Registration, Rewind functionality, and a new CodeExecutor utilizing the Vertex AI Code Execution Sandbox API. Previous updates on context compaction, resumability, ReflectRetryToolPlugin, and search tool support have been removed.
PiperOrigin-RevId: 822848112
The section detailing the first ADK community call scheduled for Oct 15, 2025, including date, time, meeting links, and agenda, has been removed.
The section detailing the first ADK community call scheduled for Oct 15, 2025, including date, time, meeting links, and agenda, has been removed.
PiperOrigin-RevId: 822843889
This release includes updates to the changelog with new features across Core, Evals, Integrations, Observability, Services, Tools, and UI, along with various bug fixes and improvements. The base CL number has also been updated.
PiperOrigin-RevId: 822730595
Since it appears in the same bubble as the rest of the LLM's response text, make it more human readable so it doesn't look out of place.
PiperOrigin-RevId: 822729061
The `BaseTool` expects the run_async to return a json-serializable object. By model_dump the McpTool result explicitly can allow what ADK runtime sees is identical to what is persisted in the session event list.
Before the change, runtime sees CallToolResult instance and Session persists its serialized dict.
https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/types.py#L916-L922
PiperOrigin-RevId: 822465432
From
```
You are an agent. Your internal name is "agent".
The description about you is "test description"
```
to
```
You are an agent. Your internal name is "agent". The description about you is "test description".
```
PiperOrigin-RevId: 822358196
To register a custom service:
- Create a factory function that takes a URI and returns an instance of your custom service. This function will parse any details it needs from the URI.
- Register your factory with the global service registry. You need to define a unique URI scheme for your service (e.g., custom).
PiperOrigin-RevId: 822310466
Merge https://github.com/google/adk-python/pull/3170
Addresses Feature Request: #3116
This PR adds a `speech_config` to the **LLM Agent configuration** for the **live use case**. When an **asynchronous LLM** call is made to the **Gemini Live API**, it prioritizes the most specific agent configuration's speech_config. If that is null, it then uses the run configuration's speech_config. Unit tests have been added to verify this behavior.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3170 from qyuo:bidi_agent_speech_config af1bd277d4f95c4a7d9aa0b16828ba3de826ce08
PiperOrigin-RevId: 822305427
Merge https://github.com/google/adk-python/pull/3194
Allow Google API toolsets to accept optional per-request headers
#3105
## Testing Plan
### Unit Tests
- ✅ Added `test_init_with_additional_headers` in `test_google_api_tool.py` to verify headers are passed to RestApiTool
- ✅ Added `test_prepare_request_params_merges_default_headers` in `test_rest_api_tool.py` to verify custom headers are merged into requests
- ✅ Added `test_prepare_request_params_preserves_existing_headers` in `test_rest_api_tool.py` to verify critical headers (Content-Type, User-Agent) are not overridden by additional_headers
- ✅ Updated `test_init` and `test_get_tools` in `test_google_api_toolset.py` to verify the parameter is properly stored and passed through
### Manual Testing
Tested with Google Ads API scenario (the original use case from issue #3105):
```python
import os
from google.adk.tools.google_api_tool import GoogleApiToolset
# Create toolset with developer-token header required by Google Ads API
google_ads_toolset = GoogleApiToolset(
client_id=os.environ["CLIENT_ID"],
client_secret=os.environ["CLIENT_SECRET"],
api_name="googleads",
api_version="v21",
additional_headers={"developer-token": os.environ["GOOGLE_ADS_DEV_TOKEN"]}
)
# Verify headers are included in API requests
tools = await google_ads_toolset.get_tools()
# Successfully made requests with the developer-token header
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3194 from Prhmma:feature/google-api-toolset-additional-headers-3105 e10489e82bfde5cf2bfd3f1bced3e1f5cea1f8b2
PiperOrigin-RevId: 822273582
Previously BuiltInCodeExecutor was missing the logic to save output files from executed code as artifacts, so images/visualizations wouldn't show up in the UI. This fix will iterate through all parts of the LlmResponse, and if any of them are images, it will save the image data using artifact_service (similar to what is done in VertexAICodeExecutor).
This fixes the backend, but there are still UI bugs that should be fixed -- events without content are currently ignored, so the image doesn't appear even though it is saved. We will add the UI fix in a separate change.
PiperOrigin-RevId: 822245140
- let _enforce_app_name_alignment warn instead of raising while caching the hint that now augments the existing “Session not found …” error
- tighten _infer_agent_origin so it ignores hidden folders (like .venv)
- make AgentTool reuse the parent runner’s app_name, stopping internal runners from conflicting in multi-agent setups
PiperOrigin-RevId: 822205860
Details:
- Adds the `StaticUserSimulator` which implements the current functionality of supplying a fixed set of user prompts for an EvalCase.
- Adds the `UserSimulatorProvider` which determines the type of user simulator required for an EvalCase (StaticUserSimulator or LlmBackedUserSimulator).
- Integrates the UserSimulatorProvider and UserSimulator into the CLI and evaluation infrastructure.
- Updates and adds unit tests for the new functionality.
- Miscellaneous updates to lay groundwork for a full implementation of the LlmBackedUserSimulator in the future.
PiperOrigin-RevId: 822198401
Merge https://github.com/google/adk-python/pull/3196
## Summary
Enhances the `AgentLoader` error message to provide clear guidance when users run `adk web` from incorrect directories.
## Motivation
During internal workshops, multiple teams encountered confusion when starting `adk web` from the wrong directory. This often happened when:
- Running `adk web my_agent/` instead of `adk web .`
- Being inside an agent directory when executing the command
- Configuring incorrect start paths during development
## Changes
- **Smart detection**: Checks if `agent.py` or `root_agent.yaml` exists in the current directory
- **Visual diagram**: Shows expected directory structure with actual agent name
- **Explicit command**: Includes `adk web <agents_dir>` usage example
- **Conditional hint**: Provides targeted guidance when user is detected to be inside an agent directory
## Example Error Message
### Before
```
ValueError: No root_agent found for 'my_agent'. Searched in 'my_agent.agent.root_agent', 'my_agent.root_agent' and 'my_agent/root_agent.yaml'. Ensure 'path/my_agent' is structured correctly, an .env file can be loaded if present, and a root_agent is exposed.
```
### After
```
ValueError: No root_agent found for 'my_agent'. Searched in 'my_agent.agent.root_agent', 'my_agent.root_agent' and 'my_agent/root_agent.yaml'.
Expected directory structure:
<agents_dir>/
my_agent/
agent.py (with root_agent) OR
root_agent.yaml
Then run: adk web <agents_dir>
Ensure 'path/my_agent' is structured correctly, an .env file can be loaded if present, and a root_agent is exposed.
HINT: It looks like you might be running 'adk web' from inside an agent directory. Try running 'adk web .' from the parent directory that contains your agent folder, not from within the agent folder itself.
```
## Testing
- ✅ Existing unit tests pass (17/22, with 5 pre-existing failures unrelated to this change)
- ✅ `test_agent_not_found_error` passes, confirming error message enhancement works correctly
- ✅ Code follows ADK contribution guidelines
## Type
- [x] Bug fix (improved error messaging)
- [ ] Feature
- [ ] Breaking change
- [ ] Documentation
## Related
Fixes#3195
---
**Tags**: #non-breaking
🤖 Generated with [Claude Code](https://claude.com/claude-code)
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3196 from jpantsjoha:fix/improve-adk-web-error-message a73b190f5b021dbe0afa8426172696ee9eeae8da
PiperOrigin-RevId: 822186700
Merge https://github.com/google/adk-python/pull/3060
## Description
Fixes#3059
This PR fixes two endpoints in `adk web` that fail when using App objects instead of bare agents.
## Changes
- **Eval execution endpoint** (line ~969): Extract root_agent from App objects before passing to LocalEvalService
- **Graph visualization endpoint** (line ~1308): Extract root_agent from App objects before graph operations
Both endpoints now properly handle both BaseAgent and App objects by checking the type and extracting `.root_agent` when needed.
## Testing Plan
### Manual E2E Testing with ADK Web
Tested with an App object that includes context caching:
```python
from google.adk.apps import App
from google.adk.agents import LlmAgent
root_agent = LlmAgent(name="MyAgent", model="gemini-1.5-pro-002")
app = App(
name="my_agent",
root_agent=root_agent,
context_cache_config=ContextCacheConfig(...)
)
```
**Before fix:**
- Graph visualization failed (tried to call agent methods on App object)
- Eval execution failed (LocalEvalService received App instead of agent)
**After fix:**
- Graph visualization works correctly
- Eval execution works correctly
- Both endpoints properly extract root_agent from App objects
## Checklist
- [x] Code follows project style (autoformat.sh passed)
- [x] Changes are focused and minimal
- [x] Issue #3059 created and referenced
- [x] Manual E2E testing completed
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3060 from ejfn:ejfn/bugfix-app-object-endpoints 01c30191bfd9487a8c8463ccf24b297cb9a4ce37
PiperOrigin-RevId: 821746910
Add a header_provider param which is a callable[ReadonlyContext, Dict[str, Any]] for users to build headers in MCPToolset
fix: https://github.com/google/adk-python/issues/3156
PiperOrigin-RevId: 820412372
This change introduces type aliases for request and event conversion functions:
- `A2ARequestToADKRunArgsConverter`: For converting A2A `RequestContext` to an `ADKRunArgs` Pydantic model.
- `AdkEventToA2AEventsConverter`: For converting ADK `Event` to a list of A2A `A2AEvent` objects.
The `convert_a2a_request_to_adk_run_args` function now returns a structured `ADKRunArgs` model instead of a generic dictionary, improving type safety.
These converter types can now be provided via the `A2aAgentExecutorConfig` to customize the conversion logic used by the `A2aAgentExecutor`. The executor defaults to the existing `convert_a2a_request_to_adk_run_args` and `convert_event_to_a2a_events` functions if no custom converters are specified.
This allows users to inject their own logic for handling request and event conversions, for example, to add custom metadata or transform data types, without modifying the core executor.
PiperOrigin-RevId: 819934960
Merge https://github.com/google/adk-python/pull/2884closes: #2883
# Fix
When put leage data into event and load it. the _pickle.UnpicklingError was occurred.
The root caurse is `DynamicPickleType` mapping `BLOB` as default in case of MySql, not `LONGBLOB`. And learge data will be able to cut off tail of data. And raise pickle error.
# What todo
Defined `LONFBLOB` as default explicitly.
# Question
Where should we code the test code like this case? I cannot found the test code the DB and table was created expectedly.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2884 from Lin-Nikaido:fix/#2883-mysql-datatype-fix 2be9b38fc3f5d5083b0b6715a2bf7b4eff5d947b
PiperOrigin-RevId: 819891727
Merge https://github.com/google/adk-python/pull/2206
### Summary
This PR adds support for `ContextWindowCompressionConfig` in `RunConfig`.
This enables context window compression using a `trigger_tokens` threshold and a sliding window with a `target_tokens` limit.
This feature is useful for managing long-running audio inputs.
### Related Issue
Closes#2188
### Testing Plan
- Added new unit test: `test_streaming_with_context_window_compression_config`
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2206 from ac-machache:support/add-context-compression-config c8a5b15cae2d2b72f331797d07ae0bbaf977ed3c
PiperOrigin-RevId: 819855786
This change removes the `convert_session_to_eval_format` function and its associated unit tests. New tests for `create_gcs_eval_managers_from_uri` are also added.
PiperOrigin-RevId: 819576620
- add a shared --structured_logs flag to adk web and adk api_server so users can opt into JSON-formatted output
- introduce CloudTraceJSONFormatter that emits structured entries and attaches current Cloud Trace/Span IDs when an OpenTelemetry context is active
- update CLI logging setup to clear duplicate stdout handlers when Cloud Logging is enabled and to reconfigure existing handlers (like from Uvicorn) so they also pick up the structured format and requested log level
With the flag disabled the CLIs keep their existing text logs; when enabled, the services now produce Cloud Logging–friendly JSON that can be correlated with distributed traces.
PiperOrigin-RevId: 818823818
Update plugin manager and built-in plugins to prioritize CallbackContext. Keep InvocationContext access for legacy plugins with adapter. Change callback docs/tests to cover the new context.
PiperOrigin-RevId: 818822267
Update plugin manager and built-in plugins to prioritize CallbackContext. Keep InvocationContext access for legacy plugins with adapter. Change callback docs/tests to cover the new context.
PiperOrigin-RevId: 818798087
This is so we don't need to worry about side effect of Loop in all agent type. Custom agent should do the same if there exists loop inside.
PiperOrigin-RevId: 818766305
This change removes the `run_evals` function and its helper `_get_evaluator` from `cli_eval.py`, as they were marked as deprecated. Corresponding test mocks and patches in `test_fast_api.py` are also removed.
PiperOrigin-RevId: 818719422
changed the LiteLLM content conversion so Part.file_data.file_uri (like the gs://…) becomes a file object with file_id, making sure GCS-backed files reach LiteLLM proxies instead of being dropped add unit tests covering both _get_content and _content_to_message_param paths for file URIs
PiperOrigin-RevId: 817658432
This change removes the `evaluate`, `_evaluate_row`, `are_tools_equal`, `_remove_tool_outputs`, `_report_failures`, and `_print_results` static methods from `TrajectoryEvaluator`, along with their corresponding unit tests. These methods were previously marked as deprecated.
PiperOrigin-RevId: 817477494
This CL updates the "What's new" section to include Resumability, ReflectRetryToolPlugin, Context compaction, and Search tool support. It also moves "Agent Config" and "Tool Confirmation" from "What's new" to "Key Features".
PiperOrigin-RevId: 817469210
The added section provides details for the community call on Oct 15, 2025, including the agenda and links to join and add to calendars.
PiperOrigin-RevId: 817457276
Agent developers can now create an eval set and add eval cases through command line itself. Adding an eval case is limited only to specifying conversation scenarios.
Sample comamnds:
- Create an eval set:
adk eval_set create \
contributing/samples/hello_world \
set_01
- Add an eval case with scenario file
Content of scenarios.json file:
'{"scenarios": [{"starting_prompt": "hello", "conversation_plan": "world"}]}'
adk eval_set add_eval_case \
contributing/samples/hello_world \
set_01 \
--scenarios scenarios.json
PiperOrigin-RevId: 817456117
The `agent_loader.load_agent` method can now return an `App` object. This change unwraps the `App` to get its `root_agent` before passing it to the graph builder, makes sure a `BaseAgent` instance is always used
PiperOrigin-RevId: 817209601
Details:
- Introduces a concept of `ConversationScenario` to represent a scenario that user simulator is supposed to follow.
- Introduces a `UserSimulator` interface, that one should implement. UserSimulator interface will be integrated with LocalEvalService in subsequent PRs.
PiperOrigin-RevId: 816883699
When there are multiple intervals and compactions, the original implementation only keep the last one. The right implementation is to keep as many compaction events/summary as the requested internals.
PiperOrigin-RevId: 816516662
This plugin intercepts tool failures, provides structured guidance to the LLM for reflection and correction, and retries the operation up to a configurable limit.
**Key Features:**
- **Concurrency Safe:** Uses locking to safely handle parallel tool
executions
- **Configurable Scope:** Tracks failures per-invocation (default) or globally
using the `TrackingScope` enum.
- **Extensible Scoping:** The `_get_scope_key` method can be overridden to
implement custom tracking logic (e.g., per-user or per-session).
- **Granular Tracking:** Failure counts are tracked per-tool within the
defined scope. A success with one tool resets its counter without affecting
others.
- **Custom Error Extraction:** Supports detecting errors in normal tool
responses
that
don't throw exceptions, by overriding the `extract_error_from_result`
method.
**Example:**
```python
from my_project.plugins import ReflectAndRetryToolPlugin, TrackingScope
# Example 1: (MOST COMMON USAGE):
# Track failures only within the current agent invocation (default).
error_handling_plugin = ReflectAndRetryToolPlugin(max_retries=3)
# Example 2:
# Track failures globally across all turns and users.
global_error_handling_plugin = ReflectAndRetryToolPlugin(max_retries=5,
scope=TrackingScope.GLOBAL)
# Example 3:
# Retry on failures but do not throw exceptions.
error_handling_plugin =
ReflectAndRetryToolPlugin(max_retries=3,
throw_exception_if_retry_exceeded=False)
# Example 4:
# Track failures in successful tool responses that contain errors.
class CustomRetryPlugin(ReflectAndRetryToolPlugin):
async def extract_error_from_result(self, *, tool, tool_args,tool_context,
result):
# Detect error based on response content
if result.get('status') == 'error':
return result
return None # No error detected
error_handling_plugin = CustomRetryPlugin(max_retries=5)
```
PiperOrigin-RevId: 816456549
Merge https://github.com/google/adk-python/pull/2857
Adds support for invoking Gemma models via the Gemini API endpoint. To support agentic function, callbacks are added which can extract and transform function calls and responses into user and model messages in the history.
This change is intended to allow developers to explore the use of Gemma models for agentic purposes without requiring local deployment of the models. This should ease the burden of experimentation and testing for developers.
A basic "hello world" style agent example is provided to demonstrate proper functioning of Gemma 3 models inside an Agent container, using the dice roll + prime check framework of similar examples for other models.
## Testing
### Testing Plan
- add and run integration and unit tests
- manual run of example `multi_tool_agent` from quickstart using new `Gemma` model
- manual run of `hello_world_gemma` agent
### Automated Test Results:
| Test Command | Results |
|----------------|---------|
| pytest ./tests/unittests | 4386 passed, 2849 warnings in 58.43s |
| pytest ./tests/unittests/models/test_google_llm.py | 100 passed, 4 warnings in 5.83s |
| pytest ./tests/integration/models/test_google_llm.py | 5 passed, 2 warnings in 3.73s |
### Manual Testing
Here is a log of `multi_tool_agent` run with locally-built wheel and using Gemma model.
```
❯ adk run multi_tool_agent
Log setup complete: /var/folders/bg/_133c0ds2kb7cn699cpmmh_h0061bp/T/agents_log/agent.20250904_152617.log
To access latest log: tail -F /var/folders/bg/_133c0ds2kb7cn699cpmmh_h0061bp/T/agents_log/agent.latest.log
/Users/<redacted>/venvs/adk-quickstart/lib/python3.11/site-packages/google/adk/cli/cli.py:143: UserWarning: [EXPERIMENTAL] InMemoryCredentialService: This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
credential_service = InMemoryCredentialService()
/Users/<redacted>/venvs/adk-quickstart/lib/python3.11/site-packages/google/adk/auth/credential_service/in_memory_credential_service.py:33: UserWarning: [EXPERIMENTAL] BaseCredentialService: This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
super().__init__()
Running agent weather_time_agent, type exit to exit.
[user]: what's the weather like today?
[weather_time_agent]: Which city are you asking about?
[user]: new york
[weather_time_agent]: OK. The weather in New York is sunny with a temperature of 25 degrees Celsius (77 degrees Fahrenheit).
```
And here is a snippet of a log generated with DEBUG level logging of the `hello_world_gemma` sample. It demonstrates how function calls are extracted and inserted based on Gemma model interactions:
```
...
2025-09-04 15:32:41,708 - DEBUG - google_llm.py:138 -
LLM Request:
-----------------------------------------------------------
System Instruction:
None
-----------------------------------------------------------
Contents:
{"parts":[{"text":"\n You roll dice and answer questions about the outcome of the dice rolls.\n You can roll dice of different sizes...\n"}],"role":"user"}
{"parts":[{"text":"Hi, introduce yourself."}],"role":"user"}
{"parts":[{"text":"Hello! I am data_processing_agent, a hello world agent that can roll many-sided dice and check if numbers are prime. I'm ready to assist you with those tasks. Let's begin!\n\n\n\n"}],"role":"model"}
{"parts":[{"text":"Roll a die with 100 sides and check if it is prime"}],"role":"user"}
{"parts":[{"text":"{\"args\":{\"sides\":100},\"name\":\"roll_die\"}"}],"role":"model"}
{"parts":[{"text":"Invoking tool `roll_die` produced: `{\"result\": 82}`."}],"role":"user"}
{"parts":[{"text":"{\"args\":{\"nums\":[82]},\"name\":\"check_prime\"}"}],"role":"model"}
{"parts":[{"text":"Invoking tool `check_prime` produced: `{\"result\": \"No prime numbers found.\"}`."}],"role":"user"}
{"parts":[{"text":"The die roll was 82, and it is not a prime number.\n\n\n\n"}],"role":"model"}
{"parts":[{"text":"Roll it again."}],"role":"user"}
-----------------------------------------------------------
Functions:
-----------------------------------------------------------
2025-09-04 15:32:41,708 - INFO - models.py:8165 - AFC is enabled with max remote calls: 10.
2025-09-04 15:32:42,693 - INFO - google_llm.py:180 - Response received from the model.
2025-09-04 15:32:42,693 - DEBUG - google_llm.py:181 -
LLM Response:
-----------------------------------------------------------
Text:
{"args":{"sides":100},"name":"roll_die"}
-----------------------------------------------------------
...
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2857 from douglas-reid:add-gemma-via-api e6d015f6a9ccbcf20ef7a7af8e4bbe1e9a5936b6
PiperOrigin-RevId: 816451001
If `EventsCompactionConfig` is provided without a `compactor`, a `SlidingWindowCompactor` is now automatically instantiated using the `root_agent`'s LLM. This simplifies configuration by providing a sensible default.
PiperOrigin-RevId: 816038579
The class is now named `LlmEventSummarizer` to better reflect that its primary function is to use an LLM to summarize events. The docstring has been updated to clarify that this class is responsible *only* for the LLM-based summarization of a given set of events, while the logic for determining *when* and *which* events form the sliding window is handled by an external component, such as an ADK Runner.
PiperOrigin-RevId: 815976264
This change introduces a new `analyze_contribution` function in `query_tool.py` which uses BigQuery ML's `CREATE MODEL` with `CONTRIBUTION_ANALYSIS` type and `ML.GET_INSIGHTS` to analyze the contribution of different dimensions to a given metric. The new function is also added to the `bigquery_toolset`.
PiperOrigin-RevId: 815849281
before this change, we estimate the token count of the contents to cache and use it to compare with the threshold user set. but that's not precise , so we use the actual prompt token count of previous llm request.
We won't create cache for the very initial request
PiperOrigin-RevId: 814484840
We updated the one of the public methods on AgentEvaluator to take in eval metric configurations using a more formal EvalConfig data model.
We also mark "criteria" field on the method as deprecated.
Updated some integration test cases.
PiperOrigin-RevId: 814314134
The root cause is an unsafe in-memory mutation. The `SaveFilesAsArtifactsPlugin` was saving a direct reference to the message part and then modifying the message list in-place. This created a race condition where downstream code could alter the original part *after* it had been saved as an artifact, leading to a corrupted state.
This CL saves a `copy.copy()` of the artifact, which create a snapshot of the data.
Also Changes the plugin to return a new `types.Content` object instead of modifying the original message in-place
PiperOrigin-RevId: 814308070
This is allow user to update session state without running the agent. e.g. if I want to test some case when session has certain state on adk web.
PiperOrigin-RevId: 814252851
Currently, the A2A Task -> ADK event conversion is producing the same events on the last two update events (the last is a status update marking the task complete)
The change here based on A2AClientEvent(task, update):
- if the update == None: handle the non-streaming task case and also streaming case for the initial task creation event
- if the update = TaskStatusUpdateEvent AND a message is set: emit an event with that message
- if a task status update AND no message is set: don't emit event (for example, the final status update)
- if the update is ArtifactUpdateEvent and it's final artifact: emit the event
PiperOrigin-RevId: 812878869
The PR does two main things:
1) Introduces a new rubric based tool use metric
2) Given that we now have two rubric based metric, we refactor and create a new RubricBasedEvaluator interface.
PiperOrigin-RevId: 811983514
mainly because http://github.com/robots.txt disallows `/*/raw/` path. using GCS HTTP URIs is more reliable with Gemini model.
PiperOrigin-RevId: 811409688
Changes include:
- Implementing missing attributes. e.g. 'gen_ai.agent.name'
- Specifying reasons for not filling out some conditionally required attributes. e.g. 'gen_ai.data_source.id'
- Specifying reasons for not including certain attributes which are specified in current semconv. e.g. inference attributes on agent spans
PiperOrigin-RevId: 811379706
this is to allow turning on debug log for debugging if some unexpected behavior observed during running cache analysis experiments.
PiperOrigin-RevId: 811189954
This is to avoid serialization issue for some fields that are not json serializable.
meanwhile restructure the debug logs in context cache manager for better debugging potential issues.
PiperOrigin-RevId: 811182492
AppDetails require two pieces of information:
1) Instructions
2) Tools
Both these pieces of information are gathered using the llm_request that was passed to the model. This approach, slightly invasive, ensures that we capture the "exact" instructions and tools that were given to the model.
PiperOrigin-RevId: 811180648
Details:
1. Data model for storing App Details (the agentic system)
As we move towards LLM as Judge metrics, we see that some of these metrics need information about the Agentic system that was used for inferencing. We add a data model to capture that.
2. Data model for Steps
We refine the concept of intermediate data. Previously it stored data in the form of a multiple lists, thereby losing out on the chronological information. This information is needed for some of the metrics. So we refine the concept of intermediate data as series of logical steps that an Agent Take.
PiperOrigin-RevId: 811122784
Merge https://github.com/google/adk-python/pull/2823
Description
This change introduces a tool_name_prefix attribute to McpToolset and McpToolsetConfig. This allows for adding a prefix to the
names of all tools within the toolset, which can help avoid naming collisions and provide better organization.
The implementation involves updating the McpToolset's __init__ and from_config methods to handle the new tool_name_prefix and
adding the corresponding field to McpToolsetConfig.
Testing Plan
A new unit test file has been added to ensure the functionality works as expected.
- `tests/unittests/tools/test_mcp_toolset.py`:
- The test_mcp_toolset_with_prefix test case verifies that the tool_name_prefix is correctly applied to the tool names
retrieved from the toolset.
- All tests were run via pytest and passed.
Related Issue
- Closes#2814
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2823 from shsha4:fix/issue-2814 e8e5b0d6d5f406d3875faf2229a96701725b7a5e
PiperOrigin-RevId: 810500616
Merge https://github.com/google/adk-python/pull/2458
**Summary**
Verifies that user-provided messages are always passed to the LLM as 'user' role, regardless of whether the role is explicitly set in types.Content. Before the current fix, if the LlmRequest from the user doesn't have the 'user' role, but has the user content, then the text is being replaced with the standard text - "Handle the requests as specified in the System Instruction." and the content from the user is completely ignored and not passed into the LLM.
**Code to replicate the problem**
```
from google.adk.agents import LlmAgent
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.genai.types import Content, Part
from google.adk.models.lite_llm import LiteLlm
from google.adk.models import LlmRequest
from google.genai import types
from pydantic import Field
import litellm
litellm._turn_on_debug()
import warnings
warnings.filterwarnings("ignore", category=UserWarning, message=".*InMemoryCredentialService.*")
import os
from dotenv import load_dotenv
# Load environment variables from the agent directory's .env file
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Define agent with output_key
root_agent = LlmAgent(
name="name_of_agent",
model=LiteLlm(model="azure/gpt-4o-mini"),
instruction="You are a customer agent to help the users with their concerns."
)
# --- Setup Runner and Session ---
app_name, user_id, session_id = "state_app", "user1", "session1"
session_service = InMemorySessionService()
runner = Runner(
agent=root_agent,
app_name=app_name,
session_service=session_service
)
print(f"Runner created for agent '{runner.agent.name}'.")
session = await session_service.create_session(
app_name=app_name,
user_id=user_id,
session_id=session_id
)
# --- Run the Agent ---
async def call_agent_async(query: str, runner, user_id, session_id):
user_message = Content(parts=[Part(text=query)])
async for event in runner.run_async(
user_id=user_id,
session_id=session_id,
new_message=user_message
):
print("event")
print(f" [Event]\n Author: {event.author}\n Type: {type(event).__name__}",
f"\n Final: {event.is_final_response()}\n Content: {event.content}")
return event
event = await call_agent_async("What is the capital of India.",runner=runner,user_id=user_id,session_id=session_id)
```
**Before the fix (current adk-python code output)**
```
00:29:24 - LiteLLM:DEBUG: utils.py:348 -
00:29:24 - LiteLLM:DEBUG: utils.py:348 - Request to litellm:
00:29:24 - LiteLLM:DEBUG: utils.py:348 - litellm.acompletion(model='azure/gpt-4o-mini', messages=[{'role': 'developer', 'content': 'You are a customer agent to help the users with their concerns.\n\nYou are an agent. Your internal name is "name_of_agent".'}, {'role': 'user', 'content': 'Handle the requests as specified in the System Instruction.'}], tools=None, response_format=None)
```
**After the fix (after resolving the fix)**
```
00:28:46 - LiteLLM:DEBUG: utils.py:349 -
00:28:46 - LiteLLM:DEBUG: utils.py:349 - Request to litellm:
00:28:46 - LiteLLM:DEBUG: utils.py:349 - litellm.acompletion(model='azure/gpt-4o-mini', messages=[{'role': 'developer', 'content': 'You are a customer agent to help the users with their concerns.\n\nYou are an agent. Your internal name is "name_of_agent".'}, {'role': 'user', 'content': 'What is the capital of India.'}], tools=None, response_format=None)
```
**Testing**
Following unit test is created to test the applied changes and added in the location as suggested in the guidelines.
adk-python\tests\unittests\models\test_base_llm.py
```
import pytest
from google.genai import types
from google.adk.models.llm_request import LlmRequest
from google.adk.models.lite_llm import _get_completion_inputs
@pytest.mark.parametrize("content_kwargs", [
# Case 1: Explicit role provided
{"role": "user", "parts": [types.Part(text="This is an input text from user.")]},
# Case 2: Role omitted, should still be treated as 'user'
{"parts": [types.Part(text="This is an input text from user.")]}
])
def test_user_content_role_defaults_to_user(content_kwargs):
"""
Verifies that user-provided messages are always passed to the LLM as 'user' role,
regardless of whether the role is explicitly set in types.Content.
The helper `_get_completion_inputs` should give normalize messages so that
explicit 'user' and implicit (missing role) are equivalent.
"""
llm_request = LlmRequest(
contents=[types.Content(**content_kwargs)],
config=types.GenerateContentConfig()
)
messages, _, _, _ = _get_completion_inputs(llm_request)
assert all(
msg.get("role") == "user" for msg in messages
), f"Expected role 'user' but got {messages}"
assert any(
"This is an input text from user." == (msg.get("content") or "")
for msg in messages
), f"Expected the user text to be preserved, but got {messages}"
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2458 from TanejaAnkisetty:bug/agent-user-content 381b01418d249b9e6bd91ebb518ff25339a8e47b
PiperOrigin-RevId: 809281620
Static instructions:
Always added to system instructions for context caching
Dynamic instructions:
Added to system instructions when no static instruction exists (for backward compatibility), OR inserted before last batch of continuous user content when static instructions exist
PiperOrigin-RevId: 809170679
1. add a context cache config in app level which will apply to all agents in the app
2. pass on cache config through invocation context to llm_reqeust
3. store cache metadata in llm_response
4. lookup old cache metadata from latest event for reusing old cache
5. create new cache if old cache cannot be reused
PiperOrigin-RevId: 809158578
Currently there is chance for Cloud Monitoring-related errors in logs during shutdown. Let's disable metrics part until it is fixed.
PiperOrigin-RevId: 808930635
The docstrings for `compaction_range` and `compacted_content` are updated to reflect that compaction is based on timestamp ranges rather than sequence IDs, and to use consistent terminology ("compacted" instead of "summarized").
PiperOrigin-RevId: 808770610
Merge https://github.com/google/adk-python/pull/2960
1. All in one authentication sample (has an IDP, Agent and the application) under `contributing/samples/authn-adk-all-in-one/`
2. Documented for all the steps.
3. OAuth 2.0 Authorization Code Grant type used by the agent.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2960 from nikhilpurwant:main dfcc821602d265c4ae7cc42eb1f5739beaad6f87
PiperOrigin-RevId: 808672120
This add `GoogleMapsGroundingTool`, a built-in tool for Gemini 2 models to ground query results with Google Maps. This tool operates internally within the model and is only available when using the VertexAI Gemini API.
PiperOrigin-RevId: 808650501
Provide a more efficient way to compact LLM context for better agentic performance.
* `app`: the top level abstraction for an ADK application. It contains an root agent, and plugins.
* `content_strategy`: the abstraction for selecting the contents for LLM request.
* `compaction_strategy`: the abstraction for compacting the events.
* Added `sequence_id` and `summary_range` in event class.
PiperOrigin-RevId: 808634224
Merge https://github.com/google/adk-python/pull/2937
**Closes #2936**
This Pull Request addresses the issue where `LlmAgent` outputs, when configured with `output_schema` and `tools`, were presenting escaped Latin characters (e.g., `\xf3` for `ó`) in the final response. This behavior occurred because `json.dumps` was being called with `ensure_ascii=True` (its default), which is not ideal for human-readable output, especially when dealing with non-ASCII characters common in many languages like Portuguese.
**Changes Proposed:**
* Modified the `_OutputSchemaRequestProcessor` in `src/google/adk/flows/llm_flows/_output_schema_processor.py` to explicitly set `ensure_ascii=False` when calling `json.dumps` for the `set_model_response` tool's output.
**Impact:**
This change ensures that all non-ASCII characters in the structured model response are preserved in their natural form, improving the readability and user experience of agent outputs, particularly for users interacting in languages with accented characters or other special symbols.
**Testing:**
The fix was verified locally by running an `LlmAgent` with an `output_schema` and confirming that responses containing Latin characters (e.g., "ação", "caminhão", "ícone") are now correctly displayed without escaping.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2937 from amenegola:fix/issue-2936-escape-chars 6cac00f97aa4cd8d8ccaa97ec5fffc74f57995dc
PiperOrigin-RevId: 808622892
- Add conformance command group with create subcommand
- Implement category/name/spec.yaml with generated-*.yaml files
- Support executing agents with queries and recording sessions
- Create test cases with recorded llm interactions and tool calls/results
Expected folder structure:
```
conformance_repo/
├── agents/ # Agent definitions - contains all config-based agents shared by test cases.
│ ├── single_basic/
│ ├── multi_basic/
│ └── single_tool_builtin/
│
└── tests/ # Test cases
├── core/ # Test category
│ ├── desc_001/ # Individual test case
│ │ ├── spec.yaml # Human-written specification
│ │ ├── generated-session.yaml
│ │ ├── generated-recordings.yaml
│ │ └── ... # Potential future generated files
│ ├── f_001/
│ │ ├── spec.yaml
│ │ ├── generated-session.yaml
│ │ ├── generated-recordings.yaml
│ │ └── ...
```
Help text:
```
-> % adk conformance create --help
Usage: adk conformance create [OPTIONS] [PATHS]...
Generate ADK conformance test YAML files from TestCaseInput specifications.
NOTE: this is work in progress.
This command reads TestCaseInput specifications from input.yaml files, executes the specified test cases against agents, and generates conformance test files with recorded agent interactions as
test.yaml files.
Expected directory structure: category/name/input.yaml (TestCaseInput) -> category/name/test.yaml (TestCase)
PATHS: One or more directories containing test case specifications. If no paths are provided, defaults to 'tests/' directory.
Examples:
Use default directory: adk conformance create
Custom directories: adk conformance create tests/core tests/tools
Options:
--help Show this message and exit.
```
PiperOrigin-RevId: 808609547
Corrected `CountInvocationPlugin` to be a class reference and added `ContextFilterPlugin` to limit the number of tool invocations kept in the context to 3.
PiperOrigin-RevId: 808591608
When start the server with `--extra_plugins=google.adk.cli.plugins.recordings_plugin.RecordingsPlugin`, it will trigger recording with expected state in session.
PiperOrigin-RevId: 808432022
This commit introduces a new ContextFilterPlugin which allows for filtering the LlmRequest contents before they are sent to the LLM. This helps in managing and potentially reducing the size of the LLM context.
The plugin provides two primary filtering mechanisms:
num_invocations_to_keep: Keeps only the specified number of the most recent user-model invocations. An invocation is defined as one or more user messages followed by a model response.
custom_filter: Allows for a user-defined callable to be applied to the contents for more flexible filtering.
Unit tests have been added to cover the different filtering scenarios, including:
Filtering by the last N invocations.
Filtering using a custom function.
Combining both filtering methods.
Handling cases with multiple user turns in a single invocation.
Ensuring no filtering occurs when options are not provided.
Gracefully handling exceptions from custom filter functions."
For example, when num_of_innovacations=2:
-----------------------------------------------------------
Contents:
{"parts":[{"text":"9"}],"role":"user"}
{"parts":[{"text":"I am sorry, I cannot fulfill this request. I need more information on what you would like me to do. I can roll a die or check prime numbers.\n"}],"role":"model"}
{"parts":[{"text":"1"}],"role":"user"}
{"parts":[{"text":"I am sorry, I cannot fulfill this request. I need more information on what you would like me to do. I can roll a die or check prime numbers.\n"}],"role":"model"}
{"parts":[{"text":"10"}],"role":"user"}
-----------------------------------------------------------
PiperOrigin-RevId: 808355316
Right now the bigquery sample agent is configured to run with OAuth, which requires some set up. This change makes it more readily usable, both locally and in AgentEngine, as Application Default Credentials (ADC) is easier to set up, and often local and AgentEngine environment already have it set up.
PiperOrigin-RevId: 808315879
Also moves the `Recordings` pydantic models into this plugins/ package.
Key features:
- Records LLM requests/responses and tool calls/results to YAML files in `generated-recordings.yaml`.
- Use session state to determine where to read and output recordings.
PiperOrigin-RevId: 807969100
Cloud Trace, Cloud Monitoring and Cloud Logging integrations are set up via OTel if otel_to_cloud CLI param/fast_api arg is provided.
This is similar to current Cloud Trace integration via trace_to_cloud, just extended to Monitoring and Logging as well.
PiperOrigin-RevId: 807385680
Cloud Trace, Cloud Monitoring and Cloud Logging integrations are set up via OTel if otel_to_cloud CLI param/fast_api arg is provided.
This is similar to current Cloud Trace integration via trace_to_cloud, just extended to Monitoring and Logging as well.
PiperOrigin-RevId: 807285744
Cloud Trace, Cloud Monitoring and Cloud Logging integrations are set up via OTel if otel_to_cloud CLI param/fast_api arg is provided.
This is similar to current Cloud Trace integration via trace_to_cloud, just extended to Monitoring and Logging as well.
PiperOrigin-RevId: 807230668
The `after_agent_callback` in plugin works similarly as the `after_agent_callback` in `base_agent.py`, e.g. it only append new content, but cannot modify the previous content.
PiperOrigin-RevId: 807162139
Similarity search tool supports similarity search on Spanner data by embedding a text query to a vector and run vector search with the embedded vector.
PiperOrigin-RevId: 806502499
Recent change to the updated A2A Client SDK broke the logging utilities. This updates those logging utilities to work with the new A2A SDK structure.
PiperOrigin-RevId: 806482017
Right now the tolls are always running against multi-region US by default. With this change the agent builder can scope the tools to data and compute in a particular BigQuery location.
PiperOrigin-RevId: 806473857
Update the bug report issue template to request minimal reproducible examples, error/stacktrace, clarify OS options, and include questions about LiteLLM usage and specific model details.
PiperOrigin-RevId: 806435953
The new test verifies that `output_audio_transcription` and `input_audio_transcription` attributes are unique to each `RunConfig` instance, preventing unintended side effects from modifying one instance.
PiperOrigin-RevId: 806405671
Switched the active model from `gemini-live-2.5-flash-preview` (for AI Studio) to `gemini-2.0-flash-live-preview-04-09` (for Vertex).
PiperOrigin-RevId: 806348640
Both are valid YAML, just with indent, it's more visually friend to see the data structure hierarchy.
Before
```
items:
- item1
- item2
- item3
```
After
```
items:
- item1
- item2
- item3
```
PiperOrigin-RevId: 806117290
The old live/bidi agents are using a cache to store context/history during agent transfer etc. As we have added support for session for live/bidi, we are now migrating the context/history cache to it. This improves scalability, efficiency and maintainability.
It introduces several changes:
* AudioTranscriber support is removed as now we are using native transcription from models.
* Transcription is returned as input_transcription/output_transcription fields and no longer as contents.
* We will return a new event with artifact references of file type of audio/pcm.(in addition to existing audio response event. So the users of this api need to do proper filtering here.)
PiperOrigin-RevId: 805997675
For advanced eval use cases, we do expect agent developers to have rubrics that are specific to an Eval Case and in some cases even specific to a single invocation/turn in the eval case conversation.
A separate PR will be created to consume this data model changes in ADK Eval.
PiperOrigin-RevId: 805588808
a. dump the discussion content to a tmp file first to avoid github redaction of environment variable
b. instruct the agent to use get_discussion_and_comments only when discussion content json is not available.
PiperOrigin-RevId: 805581573
Changes references from `gemini-1.5-flash` and `gemini-1.5-pro` to `gemini-2.5-flash` and `gemini-2.5-pro` in docstrings, default values, sample agents, and tests.
PiperOrigin-RevId: 805536434
Details:
- We plan on introducing Rubric based metrics in subsequent changes. This change introduces the data model needed that allows agent developer to provide rubrics.
- We also introduce a data model for the config that the eval system has been using for quite some time. It was loosely and informally described as a dictionary of metric names and expected thresholds. In this change, we actually formalize it using a pydantic data model, and extend it allow developers to specify rubrics as a part of their eval config.
What is a rubric based metric?
A rubric based metric is the assessment of a Agent's response (final or intermediate) along some rubric. This evaluation of agent's response significantly differs from the strategy where one has to provide a golden response.
PiperOrigin-RevId: 805488436
These tests verify that `ValueError` is raised when `Runner` is initialized without providing either an `app` instance or both `app_name` and `agent`.
PiperOrigin-RevId: 805427256
Merge https://github.com/google/adk-python/pull/2864
**Reason for this change:**
Multiple typos were found in comments, docstrings, and code throughout the codebase, which could lead to confusion and reduce code readability.
**Changes made:**
Fixed the following typos across 8 files:
1. contributing/samples/adk_answering_agent/utils.py:130: "extention" → "extension"
2. llms-full.txt:15171: "fuction" → "function"
3. src/google/adk/a2a/converters/part_converter.py:
- Line 96: "Conver" → "Convert", "reponse" → "response"
- Line 99: "suervice" → "service"
- Line 100: "accordinlgy" → "accordingly"
- Line 191: "Conver" → "Convert", "reponse" → "response"
- Line 195: "accordinlgy" → "accordingly"
4. src/google/adk/agents/base_agent.py:568: "custome" → "custom"
5. src/google/adk/evaluation/agent_evaluator.py:572: "Retruns" → "Returns"
6. src/google/adk/flows/llm_flows/basic.py:55: "outoput_schema" → "output_schema"
7. src/google/adk/flows/llm_flows/contents.py:136: "fuction_response" → "function_response"
8. src/google/adk/models/google_llm.py:138: "gemini_llm_connecton.py" → "gemini_llm_connection.py"
**Impact:**
This change will:
- Improve code documentation clarity and professionalism
- Make comments, docstrings, and code more readable and accurate
- Help prevent confusion for developers reading the code
- Ensure consistency in terminology throughout the codebase
This is a non-breaking change that only affects comments, documentation strings, and improves code clarity.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2864 from ammmr:chore-fix-typos 3cea9fcf6f21edb006b63e9258d2b82930dd961d
PiperOrigin-RevId: 805227784
The `agent-triage-pull-request` job will now only run if the pull request does not have the 'bot triaged' or 'google-contributor' labels, avoiding redundant and unnecessary triage actions.
PiperOrigin-RevId: 804732073
Use the A2A Python SDK for client support for A2A Remote clients. This enables A2A based agents that use gRPC or RESTful interfaces, as well as the jsonrpc support. This also simplifies creation of clients and provides simpler mechanisms to inject credentials and observability into the remote agent interactions.
PiperOrigin-RevId: 804711466
Changed default values for `session_service`, `artifact_service`, and `run_config` from instances of mutable classes to `None`. Instances are now created within the function body if the argument is not provided, preventing unexpected shared state across function calls.
PiperOrigin-RevId: 804624564
The system instructions for agent transfer now include a NOTE section that lists all agents available for the `transfer_to_agent` function. This also has the target agents and, if there is one that applies, the parent agent. New unit tests are added to verify the correct generation of this NOTE.
PiperOrigin-RevId: 804569691
Changed default values for `session_service`, `artifact_service`, and `run_config` from instances of mutable classes to `None`. Instances are now created within the function body if the argument is not provided, preventing unexpected shared state across function calls.
PiperOrigin-RevId: 804560641
Merge https://github.com/google/adk-python/pull/1629
close https://github.com/google/adk-python/issues/2170
### Summary
This PR introduces `GkeCodeExecutor`, a new code executor that provides a secure and scalable method for running LLM-generated code by leveraging GKE Sandbox. It serves as a robust alternative to local or standard containerized executors by leveraging the **GKE Sandbox** environment, which uses gVisor for workload isolation.
For each code execution request, it dynamically creates an ephemeral Kubernetes Job with a hardened Pod configuration, offering significant security benefits and ensuring that each code execution runs in a clean, isolated environment.
### Key Features of GkeCodeExecutor
* **Dynamic Job Creation**: Uses the Kubernetes `batch/v1` API to create a new Job for each code snippet.
* **Secure Code Mounting**: Injects code into the Pod via a temporary `ConfigMap`, which is mounted to a read-only file.
* **gVisor Sandboxing**: Enforces execution within a `gvisor` runtime for kernel-level isolation.
* **Hardened Security Context**: Pods run as non-root with all Linux capabilities dropped and a read-only root filesystem.
* **Resource Management**: Applies configurable CPU and memory limits to prevent abuse.
* **Automatic Cleanup**: Uses the `ttl_seconds_after_finished` feature on Jobs for robust, automatic garbage collection of completed Pods and Jobs.
* **Node Scheduling**: The executor uses Kubernetes `tolerations` in its Pod specification. This allows the k8s scheduler to place the execution Pod onto a **_pre-configured_** gVisor-enabled node.
* **Module Integration**: The `GkeCodeExecutor` is registered in the `code_executors/__init__.py`, making it available for use by agents. The `ImportError` handling is configured to check for the required `kubernetes` SDK.
### Execution Flow:
1. Agent invokes `GkeCodeExecutor` with the LLM-generated code.
2. The `GkeCodeExecutor` will `execute_code` – creates a temporary `ConfigMap`, and then create a k8s `Job` to run it.
3. This Job runs a standard `python:3.11-slim` container. The image is pulled once to the node and cached. The Job will mount the ConfigMap as `/app/code.py`
4. The GkeCodeExecutor will monitor the Job to completion, fetch `stdout/stderr` logs from the container, return `CodeExecutionResult` to the LlmAgent, and ensure all temp resources are deleted.
5. The calling agent formats the result and provides a final response to the user. If the result contains error, it will retry up to `error_retry_attempts` times.
PiperOrigin-RevId: 804511467
This includes:
- Test verifying multiple spans are written during E2E runner execution.
- Regression tests for the "ContextVar was created in a different Context" exceptions caused by the interplay of context based instrumentation and async generators getting indeterminately suspended.
PiperOrigin-RevId: 804333483
- Added `tests/unittests/apps/test_apps.py` with basic tests for `App` initialization.
- Modified `tests/unittests/test_runners.py` to include a test that verifies `Runner` raises a `ValueError` when both `app` and `app_name` are provided during initialization.
PiperOrigin-RevId: 803556826
This change introduces type descriptions for the functions which convert between A2A and GenAI `Part`s. It then allows passing instances of those functions to the various A2A-related functions/classes, effectively allowing users to inject their own logic for how part conversion should occur.
The benefit of this pattern is that users can create decorators around the core `Part` conversion logic, which allows them to intercept the cases they care about while delegating the ones they do not to the core converter. This is a pattern we use a lot in the A2A Python SDK.
One example where this type of logic is useful is for extensions: this allows extension logic to, for example, interpret an A2A DataPart into a FunctionResponse using extension-specific logic.
PiperOrigin-RevId: 803186799
The convention:
- If some fields(like plugin) are defined both at root_agent and app, then a error will be raised.
- app code should be located within agent.py.
- an instance named app should be created
PiperOrigin-RevId: 803155804
Before this change, other agent's reply with thought will still be inserted in the outgoing LlmRequest due to the wrong `else` statement for calling all other type of part.
This commit also refactors test_contents.py to be behavior-oriented tests, instead of implementation-oriented, and add more test cases to cover expected scenarios.
The tests are divided into the following files with different focus:
- test_contents.py: covers the basic logic of event filter;
- test_contents_branch.py: covers the behavior related to branch, which takes effect when ParallelAgent is used.
- test_contents_other_agent.py: covers the retelling behavior to include other agents' reply as context for the current agent.
- test_contents_function.py: covers the function_call/function_response rearrangement logic mainly for `LongRunningFunctionTool`.
PiperOrigin-RevId: 802759821
Before this change: `thought` flags was incorrectly removed if the current agent enables BuiltInPlanner.
After this change:
- When it's BuiltInPlanner, keep the thought flag in content history, so that model has full context of its previous thinking.
- When it's PlanReactPlanner, removes the `thought` flag in content history, so that model sees as-is when the content was generated.
PiperOrigin-RevId: 802737130
Merge https://github.com/google/adk-python/pull/2791Fixes#2789
## Summary
Forward `state_delta` from the FastAPI `/run` request to `Runner.run_async(...)`, aligning behavior with the documented
API and the `/run_sse` endpoint.
## Why
The documentation for `/run` explicitly includes:
> `state_delta` (object, optional): A delta of the state to apply before the run.
However, the non‑SSE `/run` handler did not pass this value through, so `Runner.run_async` always received `None`. The
`/run_sse` path already forwarded it correctly.
## Changes
- `src/google/adk/cli/adk_web_server.py`
- Add `state_delta=req.state_delta` to the "/run" handler’s `runner.run_async(...)` call.
- `tests/unittests/cli/test_fast_api.py`
- Add `test_agent_run_passes_state_delta` to test the fix.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2791 from pguerra-ce:fix-state-delta-missing-in-run 83eec8d28b80757e24ae900285eb59530863adbd
PiperOrigin-RevId: 802703072
The convention:
- If some fields(like plugin) are defined both at root_agent and app, then a error will be raised.
- app code should be located within agent.py.
- an instance named app should be created
PiperOrigin-RevId: 801252329
The convention:
- If some fields(like plugin) are defined both at root_agent and app, then a error will be raised.
- app code should be located within agent.py.
- an instance named app should be created
PiperOrigin-RevId: 801103084
The convention:
- If some fields(like plugin) are defined both at root_agent and app, then a error will be raised.
- app code should be located within agent.py.
- an instance named app should be created
PiperOrigin-RevId: 801084463
This will allow restricting BigQuery SQL executions to the specified project. The agent/LLM should resolve the `project_id` param for tools like `execute_sql` and sometimes they can resolve it to an unexpected value due to hallucination or ambiguity. This guardrail will protect against that situation.
PiperOrigin-RevId: 801039685
The existing `LongRunningTool` does not define a programmatic way to provide & validate structured input, also it relies on LLM to reason and parse the user's response.
For a quick start, annotate the function with `FunctionTool(my_function, require_confirmation=True)`. A more advanced flow is shown in the `human_tool_confirmation` sample.
The new flow is similar to the existing Auth flow:
- User request a tool confirmation by calling `tool_context.request_confirmation()` in the tool or `before_tool_callback`, or just using the `require_confirmation` shortcut in FunctionTool.
- User can provide custom validation logic before tool call proceeds.
- ADK creates corresponding RequestConfirmation FunctionCall Event to ask user for confirmation
- User needs to provide the expected tool confirmation to a RequestConfirmation FunctionResponse Event.
- ADK then checks the response and continues the tool call.
PiperOrigin-RevId: 801019917
Use full media types (image/jpeg, video/mp4, application/pdf) instead of suffixes (jpeg/mp4/pdf) when constructing LiteLLM payloads
This fxes compatibility with providers that validate media types (Anthropic)
Updated and added unit tests to assert full MIME types for image/video/pdf
PiperOrigin-RevId: 800685204
original tests assert too strict time boundary, now we only assert the parallel execution time should be less than sequential execution time
PiperOrigin-RevId: 800563929
The transcription change breaks the multi-agent transfer during live/bidi.
Updates `GeminiLlmConnection` to populate the `content` field of `LlmResponse` with `types.Content` and `types.Part` objects for both input and output transcriptions, instead of using dedicated transcription fields. Also removes a debug print from `audio_cache_manager.py`.
the transcription is not fully ready to be used yet so roll back the transcription change.
PiperOrigin-RevId: 799851950
- Keep original class names for backward-compatibility.
- Log warning if user instantiate the classes with original names.
- New names are more aligned with MCP SDKs convention.
PiperOrigin-RevId: 799777320
Merge https://github.com/google/adk-python/pull/2563
Currently in adk deploy cloud_run or gke, the dockerfile copies the agent code after the file permission is set. This can lead to file permission not being set correctly for the container to open and read the file.
This PR will make sure the files are copied with the permission of the user that is set in the container.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2563 from moficodes:deploy-docker d7f6df4d893af75b360e6d96ffd2640ce6076ca2
PiperOrigin-RevId: 799371070
Merge https://github.com/google/adk-python/pull/2544
The command `adk deploy cloud_run` supports limited `gcloud run deploy` args 😢.
Which makes the command fine for simple deployments...
It should support all current and future Cloud Run deployment args for the command to be widely adopted.
This can easily be done by passing through all extra args passed to `adk deploy cloud_run` to gcloud...
This PR assumes any extra args/flags passed after `AGENT_PATH` are gcloud flags.
## Example
```sh
# ADK flags
adk deploy cloud_run \
--project=$GOOGLE_CLOUD_PROJECT \
--region=$GOOGLE_CLOUD_LOCATION \
$AGENT_PATH \
# Use the -- separator for gcloud args
-- \
--min-instances=2 \
--no-allow-unauthenticated
```
This gives full Cloud Run feature support to ADK users 🤖🚀
## Test Plan
To test you can just build locally or pip install feature branch directly:
```
uv venv
uv pip install git+https://github.com/jackwotherspoon/adk-python.git
```
Deploy to Cloud Run using additional arguments following `AGENT_PATH`, such as `--min-instance=2` or `--description="Cloud Run test"`:
```sh
uv run adk deploy cloud_run \
--project=$GOOGLE_CLOUD_PROJECT \
--region=$GOOGLE_CLOUD_LOCATION \
--with_ui \
$AGENT_PATH \
-- \
--labels=test-label=adk \
--min-instances=2
```
You can click on the Cloud Run service after deployment and check the service yaml, you should see the additional label etc.
<img width="1612" height="622" alt="image" src="https://github.com/user-attachments/assets/596a260a-0052-460b-9642-c18900ccf7c9" />
Fixes https://github.com/google/adk-python/issues/2351
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2544 from jackwotherspoon:main 184a4d73f8dbe6f565ff92cf1c1fe69bb163de5e
PiperOrigin-RevId: 799252544
Merge https://github.com/google/adk-python/pull/2409
Description:
This PR Fixes: #2407
The AgentTool in /google/adk/tools/agent_tool.py uses a hardcoded user_id='tmp_user' when creating a new session for the agent it wraps. This happens within the run_async method.
code snippet
... @override async def run_async( self, *, args: dict[str, Any], tool_context: ToolContext, ) -> Any: ... session = await runner.session_service.create_session( app_name=self.agent.name, user_id='tmp_user', # <-- This is hardcoded state=tool_context.state.to_dict(), ) ...
Why is this a problem?
This hardcoding breaks the chain of user identity. When a parent agent calls a sub-agent via the AgentTool, the original user_id is lost. Any tool or logic inside the sub-agent that needs to perform user-specific actions (e.g., accessing user data from a database, retrieving user-specific memory, checking permissions) will fail or operate on the wrong context because it receives 'tmp_user' instead of the actual user's ID.
Impact:
This prevents the creation of robust, multi-agent applications where user context must be maintained across different agents and tools. It limits the utility of AgentTool to only stateless sub-agents that do not require user-specific information.
Suggested Fix:
The user_id should be retrieved from the parent context, which is available via the tool_context parameter passed into run_async. The create_session call should be updated to use the dynamic user_id from the parent session.For example, the fix might involve accessing the user ID from the tool_context.
code-snippet
session = await runner.session_service.create_session( app_name=self.agent.name, user_id=tool_context._invocation_context.user_id, state=tool_context.state.to_dict(), )
To Reproduce
Steps to reproduce the behavior:
To reproduce this bug, we need to set up a two-agent system: a ParentAgent that calls a ChildAgent using the AgentTool. The ChildAgent will have a tool designed to simply return the user_id it receives from its context.
Expected behavior
It should return the user_id of the user calling the agent,
but, in current situation we are getting tmp_user
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2409 from akshaypachpute-1998:fix-issue-2407-agent-tool-context-propogation 0c3e8656fdf11386e3ab13a3a1f2df99a396dbd1
PiperOrigin-RevId: 798315832
Merge https://github.com/google/adk-python/pull/2641
This PR adds a custom `User-Agent` header to all requests made via `RestApiTool`. This allows backend services to identify traffic originating from the ADK. The header format is `google-adk/<version> (tool: <tool_name>)`, where `<version>` is the current version of the `google-adk` package, fetched dynamically from `google.adk.version`, and `<tool_name>` is the name of the specific `RestApiTool` instance.
**Associated Issue**
Fixes#2676
**Testing Plan**
**Unit Tests**
I ran the full suite of unit tests locally to ensure the changes did not introduce any regressions. All tests passed successfully.
```bash
$ pytest ./tests/unittests
================================= 4202 passed, 2459 warnings in 44.68s ====================
```
The warnings are related to existing experimental features and are not affected by this change.
**Manual End-to-End (E2E) Test**
I performed a manual test to ensure the integrated flow works as expected.
* **Setup:** Created a clean virtual environment (`~/venvs/adk-e2e-test`) and installed the locally built `google-adk` package using `uv venv --seed` and `pip install dist/google_adk-*.whl`. Ran a custom `mock_server.py` script (using Flask) in one terminal to listen for requests and print headers. Ran a custom `run_test_tool.py` script in a second terminal to send a request using the modified `RestApiTool`.
* **Execution:** The `run_test_tool.py` script successfully sent a POST request to the mock server's `/test` endpoint. The mock server received the request and printed the headers.
**`run_test_tool.py` Output:**
```json
{
"message": "Request received successfully!"
}
```
**`mock_server.py` Output (Headers):**
```text
--- Request Received ---
Headers:
Host: 127.0.0.1:8000
User-Agent: google-adk/1.12.0 (tool: TestTool)
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Type: application/json
Content-Length: 2
------------------------
```
The `User-Agent: google-adk/1.12.0 (tool: TestTool)` header confirms the change is working as intended, dynamically fetching the package version and including the tool name.
**Checklist**
* [x] Associated issue linked
* [x] Unit tests passed
* [x] End-to-end test performed and results documented
* [x] Code formatted with `./autoformat.sh`
---
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2641 from rcsantana777:feat/add-user-agent a9a9375306c18bb7ba501276cbf76693e70a87ad
PiperOrigin-RevId: 798232385
So far we had a default docstring for the `execute-sql` tool and for non-default write modes we were concatenating more content to it. This was working fine in Python 3.9-3.12 but broke in Python 3.13 because of a nuanced difference in the string concatenation to the `__doc__` property of a function b/433914562#comment4. This change makes the docstring management more robust and readable.
PiperOrigin-RevId: 797843736
This can help to provide more context and information about the table, like parent-child relationship, and row deletion policy etc.
PiperOrigin-RevId: 797562858
Introduce `DynamicPickleType` to handle session actions, using sqlalchemy-spanner `SpannerPickleType` when the database dialect is Spanner.
Connects to a Spanner database to store session data persistently in tables.
# Example using Spanner database:
`session_service = DatabaseSessionService(db_url="spanner+spanner:///projects/project-id/instances/instance-id/databases/database-id")`
# Example adk web command:
`adk web --session_service_uri="spanner+spanner:///projects/project-id/instances/instance-id/databases/database-id"`
PiperOrigin-RevId: 797416610
Merge https://github.com/google/adk-python/pull/2212
This PR closes issue #2202
ADK was not parsing the required attribute when using LiteLLM, letting the LLM decide what is required vs not, not respecting function definitions.
## Test Plan
There's a fork of adk-python that is being running live for over 2 weeks in our production environment with millions of requests per day.
Below you can find a screenshot of the unit tests passing. I've also added one change to the test cases to cover this scenario
<img width="1904" height="483" alt="image" src="https://github.com/user-attachments/assets/5a6eb069-63ae-45a3-baca-6b01543f56fb" />
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2212 from thiagosalvatore:main 7de4037d8016389313f3fb22df40c12bac578523
PiperOrigin-RevId: 797393698
VertexAiCodeExecutor and ContainerCodeExecutor request additional dependencies, lazy load them so that when users import other names, they won't get impacted if they don't had those additional dependencies installed.
Original codes swallow the exception and log a debug log is wrong and awkward, should follow the same style as what we did in https://github.com/google/adk-python/blob/main/src/google/adk/tools/retrieval/__init__.py
PiperOrigin-RevId: 796969332
Checked with local wheel and worked as intended. The harness shows suppression works: 0 warnings for all true-like values.
This CL adds ADK_DISABLE_EXPERIMENTAL_WARNING to let the users to suppress warning messages from features decorated with @experimental.
Previously, using experimental features would always trigger a UserWarning. This change creates a way to disable these warnings, which can be good to stop flooding logs.
The warning is suppressed if ADK_DISABLE_EXPERIMENTAL_WARNING is set to a truthy value such as "true", "1", "yes", or "on" (case-insensitive).
Added unit tests to make sure:
Warning suppression for functions and classes when the env var is set.
Case-insensitivity and various truthy values for the env var.
Loading the env var from a .env file.
PiperOrigin-RevId: 796649404
* feat: adding build image to deploy cloud_run options
Gives the ability for a user to set the build image for the deployment step to Cloud Run. Currently it is hard coded to python:3.11-slim, and this is still the default, but this allows that value to be overriden.
* fix: applied formatting scripts
testing:
Added tests to ensure the behavior of the cli remains consistent with when used or omitted.
* chore: next time run the formatter before you commit.
---------
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
This change keeps dependencies to their major versions, but for the pre 1.0.0 releases pinned to minor releases as they could have breaking changes.
PyYAML: Version 7.0 is in development and could have breaking changes
absolufy-imports: The package is archived and no longer maintained.
anyio: Follows SemVer, so version 5.0 could have breaking changes.
authlib: Follows a SemVer-like pattern, so version 2.0 could have breaking changes.
click: A mature library, version 9.0 is the expected boundary for breaking changes.
fastapi: As a pre-1.0 library, the next minor release could have breaking changes.
google-api-python-client: Although in maintenance, version 3.0 could still have breaking changes.
google-cloud-aiplatform: Follows SemVer, so breaking changes are expected in version 2.0.
google-cloud-secret-manager: A stable Google library, version 3.0 could lead to breaking changes.
google-cloud-speech: A stable Google library, version 3.0 could lead to breaking changes.
google-cloud-storage: A stable Google library.
google-genai: As an official Google SDK, version 2.0 is the expected boundary for breaking changes.
graphviz: As a pre-1.0 library, the next minor release could have breaking changes.
mcp: As an SDK, version 2.0 is the boundary for potential breaking changes.
opentelemetry-api: Follows SemVer; version 2.0 could have breaking changes.
opentelemetry-exporter-gcp-trace: It's tied to the v1 OpenTelemetry API, so version 2.0 would likely be a breaking change.
opentelemetry-sdk: It's coupled to the v1 API, so version 2.0 would likely be a breaking change.
pydantic: This stops upgrades to the incompatible version 3.0 after its major 2.0 rewrite.
python-dateutil: Follows to SemVer, making version 3.0 the boundary for potential breaking changes.
python-dotenv: Locks to stable version 1.0 major release.
requests: As a more mature library, version 3.0 is boundary for breaking changes.
sqlalchemy: This locks the dependency to the stable version 2.0 API after its major rewrite.
starlette: As a pre-1.0 library, the next minor release could have breaking changes.
tenacity: This is a mature library, version 9.0 is boundary for breaking changes.
typing-extensions: Major versions are tied to large typing changes in Python itself.
tzlocal: The library has a history of introducing breaking API changes between major versions.
uvicorn: As a pre-1.0 library, the next minor release could have breaking changes.
watchdog: As a stable library, version 7.0 could have breaking changes.
websockets: Follows SemVer, so version 16.0 is the boundary for breaking changes.
PiperOrigin-RevId: 794677571
Verified with uv on Python 3.12 and 3.13 using the same ignores as CI.
3.12:
uv python install 3.12 && uv venv --python 3.12 .venv && source .venv/bin/activate
uv sync --extra test --extra eval --extra a2a
python -m pytest tests/unittests --ignore=tests/unittests/artifacts/test_artifact_service.py --ignore=tests/unittests/tools/google_api_tool/test_googleapi_to_openapi_converter.py
3.13: repeated the above with 3.13 (separate env)
Result: All unit tests passed
PiperOrigin-RevId: 794669437
Corrects a typo in the `StreamableHTTPConnectionParams` docstring, changing "SSE" to "Streamable HTTP" to accurately reflect the referenced client.
PiperOrigin-RevId: 794424727
For Vertex model backend, we send response back. This doesn't work for streaming tools that the return type is AsyncGenerator. So the fix here is to ignore the return type when it's AsyncGenerator.
We can't distinguish streaming vs non-streaming tool with AsyncGenerator though as LiveRequestQueue is optional in streaming tool.
Adds an `ignore_response` option to `build_function_declaration` to skip including the return type in the function declaration. This is enabled for tools that return `AsyncGenerator`, as the model does not yet support understanding these return types, while streaming tools can still handle them. Also, removes redundant return statements in `_get_mandatory_params`.
PiperOrigin-RevId: 794392846
This is to address the name conflict issue of tools returned by different toolset. Mainly it's to give each toolset a namespace.
We have a flag `add_tool_name_prefix` to decide whether to apply this behavior
We have a `tool_name_prefix` to let client specify a custom prefix, if not set , toolset name will be used as prefix.
PiperOrigin-RevId: 794306796
Merge https://github.com/google/adk-python/pull/1815
fix: path parameter extraction for complex Google API endpoints
- Fix GoogleApiToOpenApiConverter to handle path parameters in complex endpoints like /v1/documents/{documentId}:batchUpdate
- Use Google Discovery Document 'location' field
- Add comprehensive test suite for Google Docs batchUpdate functionality
- Verify parameter location handling for complex endpoint patterns
- Test schema validation for BatchUpdateDocumentRequest/Response
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1815 from goldylocks87:fix-issue-1814-path-parameter-extraction af5508ec6975b1ccbc34931a0041e422ee259c16
PiperOrigin-RevId: 794301898
Spanner toolset support basic operations to interact with Spanner table metadata and query results.
Consolidate BigQueryTool into generic GoogleTool, so that BigQueryToolset and SpannerToolset can share.
PiperOrigin-RevId: 794259782
The issue was caused by a breaking change in Python 3.13's inspect.cleandoc() function that made it more conservative about whitespace handling:
Root Cause:
- Python 3.12-: inspect.cleandoc() used line.lstrip() - strips all whitespace (spaces, tabs, etc.)
- Python 3.13+: inspect.cleandoc() uses line.lstrip(' ') - strips only space characters
PiperOrigin-RevId: 793921360
Demonstrates intelligent triage system with root planning agent and parallel
execution agents.
Use session state to store the execution plan and coordinate with other specialized agents.
Check out README.md for more details.
PiperOrigin-RevId: 793884758
1. Allow developers to specify output schema and tools together.
2. If both are specified, do the following:
2.1 Do not set output schema on the model config
2.2 Add a special tool called set_model_response(result)
2.3 `result` has the same schema as the requested output_schema
2.4 Instruct the model to use set_model_response() to output its final result, rather than output text directly.
2.5 When the set_model_response() is called, ADK will extract its content and put it in a text part, so the client would treat it as the model response.
PiperOrigin-RevId: 792686011
The connection_params argument in the constructor is split into four arguments in the config class because some of them have identical fields. In order to identify which is which, a separate name is more convenient.
PiperOrigin-RevId: 791965995
original codes try to eagerly import VertexAiRagRetrieval while it doesn't want to raise error if client try to import other names in this package and dependencies of VertexAiRagRetrieval is missing. so it swallow the import error which doesn't make sense, given vertex sdk is a must have for VertexAiRagRetrieval, we should fail fast.
this fix achieve the same purpose but fail fast if client try to import VertexAiRagRetrieval from this package and miss certain dependencies (e.g. vertex sdk)
PiperOrigin-RevId: 791759776
Previous implementation doesn't pass the actual handle to server. Now we cache the handle and pass it over when reconnection happens.
To enable:
run_config = RunConfig(
session_resumption=types.SessionResumptionConfig(transparent=True)
)
PiperOrigin-RevId: 791308462
1. given we are running parallel functions in one event loop (one thread) , we should use async lock instead of thread lock
2. test three kind of functions:
a. sync function
b. async function that doesn't yield
c. async function that yield
PiperOrigin-RevId: 791255012
Merge https://github.com/google/adk-python/pull/2327
`adk run --help` (adk 1.9.0)
```
--replay FILE The json file that contains the initial state of the
session and user queries. A new session will be created
using this state. And user queries are run againt the
newly created session. Users cannot continue to interact
with the agent.
```
```
$ git grep againt
src/google/adk/cli/cli_tools_click.py: " queries are run againt the newly created session. Users cannot"
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2327 from ftnext:fix-typo-run-replay-help 77cae65a235d9119810fe3d209910562672713c8
PiperOrigin-RevId: 790872246
1. if a function has no return type annotation, we should treat it as returning any type
2. we use empty schema (with `type` as None) to indicate no type constraints and this is already supported by model server
PiperOrigin-RevId: 789808104
Due to reasons that are being investigated, some of the recent changes got unintentionally reverted. We are adding those back in this PR.
PiperOrigin-RevId: 789384063
GitHub workflows triggered by `pull_request` events from forked repositories do not have access to secrets by default due to security considerations.
PiperOrigin-RevId: 789011890
The test test_token_exchange_not_supported was slow because of an incorrect monkeypatch target. The test was patching google.adk.auth.auth_handler.AUTHLIB_AVAILABLE, but the actual OAuth2 exchange logic uses a different AUTHLIB_AVAILABLE variable in google.adk.auth.exchanger.oauth2_credential_exchanger.
What was happening:
Test set auth_handler.AUTHLIB_AVAILABLE = False
AuthHandler.exchange_auth_token() called OAuth2CredentialExchanger.exchange()
But oauth2_credential_exchanger.AUTHLIB_AVAILABLE was still True
The exchanger attempted real OAuth2 token exchange with client.fetch_token()
This made actual network calls to OAuth2 endpoints, causing timeouts and delays
PiperOrigin-RevId: 788576949
This agent will post a comment if the PR is not following our contribution guides or add a label and reviewer for the PR if it passes the guide check.
PiperOrigin-RevId: 788511767
This endpoint could be used by ADK Web to dynamically know:
- What are the available eval metrics in an App
- A description of those metrics
- A value range supported by those metrics
We also update the metric registry to make it mandatory to supply these details. The goal is to improve usability and interpretability of the eval metrics.
PiperOrigin-RevId: 787277695
Merge https://github.com/google/adk-python/pull/869
How to reproduce the error:
```
from google.adk.code_executors import UnsafeLocalCodeExecutor
from google.adk.code_executors.code_execution_utils import CodeExecutionInput
result = UnsafeLocalCodeExecutor().execute_code(
invocation_context=None,
code_execution_input=CodeExecutionInput(
code='''
import math
def pi():
return math.pi
print(pi())
'''
)
)
print(result)
```
output:
```
CodeExecutionResult(stdout='', stderr="name 'math' is not defined", output_files=[])
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/869 from qieqieplus:main 63f557bbd3b7aa5c2801f5cc9e022d3364177308
PiperOrigin-RevId: 787145189
Merge https://github.com/google/adk-python/pull/2109Fixes#2105
## Problem
When integrating Google ADK with Langfuse using the @observe
decorator, the usage details displayed in Langfuse web UI were
incorrect.
The root cause was in the telemetry implementation where
total_token_count was being mapped to gen_ai.usage.output_tokens
instead of candidates_token_count.
- Expected mapping:
- candidates_token_count → completion_tokens (output tokens)
- prompt_token_count → prompt_tokens (input tokens)
- Previous incorrect mapping:
- total_token_count → completion_tokens (wrong!)
- prompt_token_count → prompt_tokens (correct)
## Solution
Updated trace_call_llm function in telemetry.py to use
candidates_token_count for output token tracking instead of
total_token_count, ensuring proper token count reporting to
observability tools like Langfuse.
## Testing plan
- Updated test expectations in test_telemetry.py
- Verified telemetry tests pass
- Manual verification with Langfuse integration
## Screenshots
**Before**
<img width="1187" height="329" alt="Screenshot from 2025-07-22 20-20-33" src="https://github.com/user-attachments/assets/ad5fc957-64a2-4524-bd31-0cebb15a5270" />
**After**
<img width="1187" height="329" alt="Screenshot from 2025-07-22 20-21-40" src="https://github.com/user-attachments/assets/3920df2a-be75-47e0-9bd0-f961bb72c838" />
_Notes_: From the screenshot, there's another problem: thoughts_token_count field is not mapped, but this should be another issue imo
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2109 from tl-nguyen:fix-telemetry-token-count-mapping 3d043f558b5f8bcb2c6e0370e2cc4c0ff25d1f4a
PiperOrigin-RevId: 786827802
Merge https://github.com/google/adk-python/pull/2148
This PR fixes#2071 exception string from `pip install google-adk[eval]` to `pip install "google-adk[eval]"` which makes it compatible for all the bash, zsh and other terminals
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2148 from kavinkumar807:fix-module-not-found-exception-string-in-eval 914281006a0e162665c0933d0c0ee0c37eb397cf
PiperOrigin-RevId: 786752261
This commit adds support for the session resumption configuration in the run_config.
The SessionResumptionConfig is added to RunConfig to allow the user to set up a configuration for session resumption(only transparent mode for now).
There are two modes of session resumption: manual and transparent. In manual mode, you have to manually bookkeeping the session information and restarts the session which is tricky to do right now. In transparent mode, the server does the bookkeeping for you and no hassle on ADK side. For now, the transparent mode should be enough.
Also, added the relevant unit tests to check that every possible configuration is set properly and the run_config is correctly populated.
This is needed for supporting the new session resumption feature.
PiperOrigin-RevId: 786549455
This plugin helps printing all critical events in the console. It is not a replacement
of existing logging in ADK. It rather helps terminal based debugging by showing all logs in the console, and serves as a
simple demo so everyone could develop their own plugins.
PiperOrigin-RevId: 786470637
This CL add new callbacks in plugin system:
- `on_tool_error_callback`
- `on_model_error_callback`
This allow the user to create plugins that can handle errors.
PiperOrigin-RevId: 786469646
Merge https://github.com/google/adk-python/pull/2138
This missing space leads to an error when deploying to cloud_run that says "No option --a2a/apps/agents"
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2138 from andrewlarimer:fix--add-space-to-allow-adk-deploy-cloud_run---a2a 47831f10e1f7f6c27b5f6b8c102b2f7db4619778
PiperOrigin-RevId: 786459787
With this change we ensure that all three eval entry points, web, cli and pytest use the common LocalEvalService.
Updates to web and cli happened in a previous change.
PiperOrigin-RevId: 786445632
Mainly it's due to GenAI sdk changed their header of genai SDK versions, we have UT to verify that ADK or ADK users won't override their headers. Updated the header accordingly in the UT.
PiperOrigin-RevId: 786334741
Please set --log_level to DEBUG, if you are interested in having those API request and responses in logs.
NOTE: Generally it is not recommended to have DEBUG log level for services that run in a production setting. It is our recommendation to only use DEBUG log level in a debug or development setting.
PiperOrigin-RevId: 785972338
Merge https://github.com/google/adk-python/pull/1959
### What
Fix misleading comment.
```diff
- # Make sure a malicious user can obtain a session and events not belonging to them
+ # Make sure a malicious user **cannot** obtain a session or events not belonging to them
```
### Why
The previous wording contradicted the assertion `assert len(session_mismatch.events) == 0`, which verifies that a malicious user **cannot** access another user’s session or events.
### Testing plan
Docs-only change.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1959 from mthorme:fix-comment-session-mismatch b1f139af340bd240d40ed58f5dea3274c3a3bd83
PiperOrigin-RevId: 785908548
This change takes cares of SQL results containing values that are not json serializable (e.g. datetime, bignumeric) by converting them to their string representation.
PiperOrigin-RevId: 785719997
We update both adk web run eval endpoint and adk eval cli to use the LocalService. The old method is marked as deprecated and will be removed in later PRs.
PiperOrigin-RevId: 785612708
Fixes#423
Related to #1670
- This avoids the `GeneratorExit` error thrown, which would crash OTel metric collection and cause `Failed to detach context` error.
- This also allows all function calls are processed when exit_loop is called together with other tools in the same LLmResponse.
A sample agent for testing:
```
from google.adk import Agent
from google.adk.agents.loop_agent import LoopAgent
from google.adk.tools.exit_loop_tool import exit_loop
worker_1 = Agent(
name='worker_1',
description='Worker 1',
instruction="""\
Just say job #1 is done.
If job #1 is said to be done. Call exit_loop tool.""",
tools=[exit_loop],
)
worker_2 = Agent(
name='worker_2',
description='Worker 2',
instruction="""\
Just say job #2 is done.
If job #2 is said to be done. Call exit_loop tool.""",
tools=[exit_loop],
)
work_agent = LoopAgent(
name='work_agent',
description='Do all work.',
sub_agents=[worker_1, worker_2],
max_iterations=5,
)
root_agent = Agent(
model='gemini-2.0-flash',
name='hello_world_agent',
description='hello world agent that can roll a check prime',
instruction="""Hand off works to sub agents.""",
sub_agents=[work_agent],
)
```
PiperOrigin-RevId: 785538101
Merge https://github.com/google/adk-python/pull/1195
## Summary
Updated the Toolbox Agent documentation to address a critical missing dependency that prevents the agent from running successfully.
## Changes Made
- **Added missing dependency**: Documented that `toolbox-core` must be installed via `pip install toolbox-core`
- **Improved documentation structure**: Added clear section numbering and better organization
- **Enhanced readability**: Fixed grammar, capitalization, and formatting throughout
- **Added Prerequisites section**: Set clear expectations before installation begins
- **Clarified optional steps**: Made it clearer when database creation can be skipped
## Problem Solved
The original documentation was missing a crucial step - installing the `toolbox-core` package. Without this dependency, users encounter an `ImportError: No module named 'toolbox-core'` when trying to use the `ToolboxToolset` class in ADK. This fix ensures users can successfully set up and run the agent without encountering import errors.
## Testing
- Verified the installation steps work correctly with the added dependency
- Confirmed the agent runs successfully after following the updated documentation
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1195 from designcomputer:patch-1 b90c71fe95aa09a3dca069e91f14791f557ab2e3
PiperOrigin-RevId: 785487495
Merge https://github.com/google/adk-python/pull/1130
This enables the use of the `model-optimizer-*` family of models in vertex, as per the [documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/vertex-ai-model-optimizer#using-vertex-ai-model-optimizer).
To use this, ensure your location is set to `global` and pass a model optimizer model to an agent:
```python
root_agent = Agent(
model="model-optimizer-exp-04-09",
name="fast_and_slow_agent",
instruction="Answer any question the user gives you - easy or hard.",
generate_content_config=types.GenerateContentConfig(
temperature=0.01,
model_selection_config=ModelSelectionConfig(
feature_selection_preference=FeatureSelectionPreference.BALANCED
# Options: PRIORITIZE_QUALITY, BALANCED, PRIORITIZE_COST
)
),
)
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1130 from calvingiles:feat-model-optimizer 1a76bfa22420edb07d83415dcea6dd0114084e8e
PiperOrigin-RevId: 784921913
Now the LangchainTool can wrap:
* Langchain StructuredTool (sync and async).
* Langchain @Tool (sync and async).
This enhance the flexibility for user and enables async functionalities.
PiperOrigin-RevId: 784728061
**Highlights:**
- **Callback Chaining:** Now supports a list of before and after callbacks, as in the non-live version. Callbacks are executed in order, stopping when one returns a response.
- **Unit Tests:** Added new unit tests for before and after callbacks, async and sync versions, callback chains and mixed callbacks.
- **Sample Agent:** Introduced a new example agent with multiple callbacks showing various behaviors: audit, security, validation, and enhancement. This provides practical usage examples.
PiperOrigin-RevId: 783884562
This change adds activity start and end signals to the LiveRequestQueue,
allowing clients to manually control the start and end of user input in
streaming sessions when automatic voice activity detection is disabled.
The LiveRequestQueue allows users to send messages to the model with the following semantics:
- `content`: sends turn-by-turn content.
- `blob`: sends a media blob for realtime streaming (e.g., audio).
- `activity_start`: indicates the beginning of an activity.
- `activity_end`: indicates the end of an activity.
- `close`: closes the connection.
GeminiLLMConnection has been updated to send the new activity signals to the backend.
This change is a necessary to support clients (e.g. voice assistants) that do not want to use automatic voice activity detection. In this case, the client will be responsible to send the `activity_start` signal when the user starts talking, and `activity_end` when the user finishes talking.
To test the change:
run_config = RunConfig(
realtime_input_config=types.RealtimeInputConfig(
automatic_activity_detection=types.AutomaticActivityDetection(
disabled=True,
),
)
)
import threading # Add this import
def thread_target():
# Define the async operations to run in the background.
async def background_task():
live_request_queue.send_activity_start()
# live_request_queue.send_content(
# content=types.Content(
# role='user',
# parts=[types.Part.from_text(text="hi, what's the time?")],
# )
# )
await asyncio.sleep(3)
live_request_queue.send_activity_end()
PiperOrigin-RevId: 783882447
1. credential service may be accessed by callbacks
2. plan to add load_credential and save_credential method in CallbackContext (see cl/782158513) given customer has requirement to access credential service themselves. (see https://github.com/google/adk-python/issues/1816)
It's backward compatible given CallbackContext is parent class of ToolContext
PiperOrigin-RevId: 783480378
This is to support model path like :
projects/265104255505/locations/us-central1/publishers/google/models/gemini-2.0-flash-001"
PiperOrigin-RevId: 783413351
This version of the EvalSetsManager is intended to support two main behaviors
1) The agent developer wants to bring in their own eval set file, which is usually the case with `adk eval` cli. Once their eval sets are uploaded into this version of the eval sets manager, the EvalSetManager could be handed over to the Eval system for running evals.
2) As a part of AgentEvaluator testing, we expect developers to supply Eval cases in json files. The in-memory version of the EvalSetsManager will help us run those test cases using LocalEvalService.
PiperOrigin-RevId: 783198788
When get session is being called on a session with more than 1 page of events (100+), the response of the subsequent listevents calls fails due to missing parsing logic. This change fixes the processing of the listevents responses.
PiperOrigin-RevId: 783166959
1) raise explicit error if the response event contains responses against multiple function call events
2) merge all function responses for the corresponding function call event
PiperOrigin-RevId: 782154577
According to a2a protocol task artifact is a different concept from adk artifact.
if a task is completed the final result should be in task artifact.
PiperOrigin-RevId: 782154265
This change:
- Introduces the LocalEvalService Class.
- Implements only the "perform_inference" method. Evaluate method will be implemented in the next CL.
- Adds required test coverage.
PiperOrigin-RevId: 781781954
This change integrates the plugin system with ADK. PluginManager is attached to the invocation context similar to session/artifact/memory.
It includes integrations with following ADK internal callbacks:
* App callbacks: Integrated in the BaseRunner class, in run_async and run_live
* On Message callbacks: Integrated in the BaseRunner class, triggers on run_async.
* Agent callbacks: Integrated in the BaseAgent class. Leveraging the existing *callback functions
* Model callbacks: Integrating in the base_llm_flow.
* Tool callbacks: Integrated in functions.py, wrapped around the code for agent tool_callbacks
Sample code to use plugins:
```python
# Add plugins to Runner
runner = Runner(
app_name="my-app",
agent=root_agent,
artifact_service=artifact_service,
session_service=session_service,
memory_service=memory_service,
plugins=[
MySamplePlugin(),
LoggingPlugin(),
],
)
```
PiperOrigin-RevId: 781746586
Plugin is a collection of callbacks (lifecycle hooks), including callbacks for Agent, Tools, Model and App. It helps developers to add customizations and change behaviors of their agent application easily
This is the first change that introduces only the base interfaces based on the doc.
plugins folder is generated with `create_symlink.sh plugins`
PiperOrigin-RevId: 781745044
Including basic fields in configs, the from_config() methods and the JSON schema. Other fields will be added in following PRs.
PiperOrigin-RevId: 781660569
Even though InMemoryMemoryService is intended only for testing and local development, we eliminate a potential source of bugs during prototyping by providing a thread-safe InMemoryMemoryService.
PiperOrigin-RevId: 781554006
- Allow run_async to break on partial events instead of raising ValueError
- Generate aggregated streaming content regardless of finish_reason
- Add error_code and error_message to final streaming responses if model response is interrupted.
PiperOrigin-RevId: 781377328
This commit includes a number of new tests for live streaming with function calls. These tests cover various scenarios:
- Single function calls
- Multiple function calls
- Parallel function calls
- Function calls with errors
- Synchronous function calls
- Simple streaming tools
- Video streaming tools
- Stopping a streaming tool
- Multiple streaming tools simultaneously
The tests use mock models and custom runners to simulate the interaction between the agent, model, and tools. They verify that function calls are correctly generated, executed, and that the expected data is returned.
PiperOrigin-RevId: 781318483
This would allow users to easily make a copy of the agents they built without having to add too much boilerplates. This promotes code reuse, modularity and testability of agents.
PiperOrigin-RevId: 781214379
This PR extends the existing Streaming tests to consider new configurations that have been added, including:
- `output_audio_transcription`
- `input_audio_transcription`
- `realtime_input_config`
- `enable_affective_dialog`
- `proactivity`
These configurations are tested individually and also combined, to cover all the possibilities, increasing the testing coverage and ensuring everything is working as expected.
In addition, the new configuration values are also validated to be sure they are properly initialized.
PiperOrigin-RevId: 780178334
This explains the high-level architecture and philosophy of the ADK project.
It can also be feed into LLMs for vibe-coding.
PiperOrigin-RevId: 780178125
fix: Use `inspect.signature()` instead of `typing.get_type_hints()` to find the LiveRequestQueue.
Motivation: `typing.get_type_hints()` may raise errors in complex scenarios where type annotation is not available.
Add live_bidi_streaming_tools_agent example to show how to use the live streaming feature.
PiperOrigin-RevId: 780160921
Adds a description for docstring and comments in the AGENTS.md and adds a section for Versioning that describes how ADK follows Semantic Versioning 2.0.0
PiperOrigin-RevId: 778667398
test: refine test_session_state in test_session_state to catch event leakage
fix: revert app name to my_app for test_session_state test
style: fix pyink style warnings
fix: add app_name to filter as per suggestion from rpedela-recurly
We add a new metric for evaluating safety of Agent's response to ADK Eval. We delegate the actual implementation to Vertex Gen AI Eval SDK, so using this metric will require GCP project.
As a part of this change, we created (refactored) a simple Facade for vertex gen ai eval sdk.
PiperOrigin-RevId: 778580406
The LLM occasionally includes an unexpected 'parameters' argument when calling tools, specifically observed with 'transfer_to_agent'. This change makes FunctionTool.run_async more robust by filtering arguments against the function signature before invocation.
This resolves issue #1637.
Update test_function_tool.py
fix typing
fix: add `from __future__ import annotations`
`grep -L` returns status 1 when there are modified files that don't have the `from __future__ import annotations` pattern. Previously if this happens, the entire GitHub action by default will stop and exit with status 1. Adding `|| true` will prevent this from happening and continue the workflow.
PiperOrigin-RevId: 778246018
Bug: When a model emits a stream of tokens, it sometimes emits a final chunk of whitespace or no content. The agent was trying to parse that content into JSON, causing a validation error.
Fix: If a model is expected to return JSON and the last streamed token is empty/whitespace, the agent will no longer try to parse it, and exit gracefully.
New unit tests confirm the scenario and the fix.
PiperOrigin-RevId: 777609415
This example include multi agents:
- Root agent.
- Sub agent for Rolling Dice.
- Sub agent for checking primes.
Added README.md to demonstrate how to use it.
PiperOrigin-RevId: 777599625
This change adds a new enum value which the agent builder can pass in the `BigQueryToolConfig` to allow limited writes to the `execute_sql` tool.
PiperOrigin-RevId: 776661744
Fixes https://github.com/google/adk-python/issues/1180
We are using `func.now()` to set the `onupdate` time for db, when SQLAlchemy generates the SQL to build the database, it actually translates `func.now()` into `NOW()` or `CURRENT_TIMESTAMP`. The value it returns depends on the database server settings. For example, if the global/default timezone for a db is set to be UTC, the update time will be set to be a UCT time; if the global time zone for a db is set to be a local time zone (e.g. America/Los_Angeles), the update time will be a local time.
Normally, the best practice is to set database server to use UTC. Applications will convert it into different time zones as needed.
For SQLite, there is no way to config the default timezone, it will just treat it as UTC. But because it is a naive datetime (with no timezone info), python will assume it is a local time and then covert it into a UTC, which is why we see the bug (e.g. we create a session at 2025-06-17 12:49:33 local time, but when we read the session, its last update time is 2025-06-17 19:49:33 local time).
The solution is converting the native datatime to be timezone aware before `.timestamp()`.
The change in this CL only affects SQLite database.
PiperOrigin-RevId: 776654443
Merge https://github.com/google/adk-python/pull/1679
Contributing doc says to do the following:
```sh
uv sync --extra test --extra eval
pytest ./tests/unittests
```
If you follow this the tests will fail:
```sh
tests/unittests/a2a/executor/test_task_result_aggregator.py:27: in <module>
from a2a.types import Message
E ModuleNotFoundError: No module named 'a2a'
```
This makes sense since the `a2a` package is not part of ADK's core dep, it is an extra:
https://github.com/google/adk-python/blob/e79651cd86ba3f0c998109f2140f1db2cab78708/pyproject.toml#L79-L83
Thus for a2a tests to pass we must include the extra in the sync command:
```sh
uv sync --extra test --extra eval --extra a2a
pytest ./tests/unittests
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1679 from jackwotherspoon:main c1a536780409065db817088a8d5ed5979cca8d8f
PiperOrigin-RevId: 776617515
Additionally, few other small changes.
* Updated a test fixture to support the latest eval data schema. Somehow I missed doing that previously.
* Updated the `evaluation_generator.py` to use `run_async`, instead of `run`.
* Also, raise an informed error when dependencies required eval are not installed.
* Also, changed the behavior of AgentEvaluator.evaluate method to run all the evals, instead of failing at the first eval metric failure.
PiperOrigin-RevId: 775919127
a. fix function call long running id matching logic
b. fix error code conversion logic
c. add input required and auth required status conversion logic
d. add a2a Task/Message to ADK event converter
f. set task id and context id from input argument
PiperOrigin-RevId: 775860563
**Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.**
### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #_issue_number_
- Related: #_issue_number_
**2. Or, if no issue exists, describe the change:**
_If applicable, please follow the issue templates to provide as much detail as
possible._
**Problem:**
_A clear and concise description of what the problem is._
**Solution:**
_A clear and concise description of what you want to happen and why you choose
this solution._
### Testing Plan
_Please describe the tests that you ran to verify your changes. This is required
for all PRs that are not small documentation or typo fixes._
**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [ ] All unit tests pass locally.
_Please include a summary of passed `pytest` results._
**Manual End-to-End (E2E) Tests:**
_Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix._
### Checklist
- [ ] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
- [ ] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have added tests that prove my fix is effective or that my feature works.
- [ ] New and existing unit tests pass locally with my changes.
- [ ] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.
### Additional context
_Add any other context or screenshots about the feature request here._
console.log(`PR #${prNumber} not found or inaccessible:`, error.message);
continue;
}
// Only close if PR is still open
if (pr.data.state !== 'open') {
console.log(`PR #${prNumber} is already ${pr.data.state}, skipping`);
continue;
}
const author = pr.data.user.login;
try {
// Add comment with commit reference
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
body: `Thank you @${author} for your contribution! 🎉\n\nYour changes have been successfully imported and merged via Copybara in commit ${commitSha}.\n\nClosing this PR as the changes are now in the main branch.`
@@ -34,73 +33,104 @@ was for a different project), you probably don't need to do it again.
Visit <https://cla.developers.google.com/> to see your current agreements or to
sign a new one.
## Review our community guidelines
### Review our community guidelines
This project follows
[Google's Open Source Community Guidelines](https://opensource.google/conduct/).
# Contribution workflow
### Code reviews
## Finding Issues to Work On
All submissions, including submissions by project members, require review. We
use GitHub pull requests for this purpose. Consult
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
information on using pull requests.
- Browse issues labeled **`good first issue`** (newcomer-friendly) or **`help wanted`** (general contributions).
- For other issues, please kindly ask before contributing to avoid duplication.
## Contribution workflow
### Finding Issues to Work On
## Requirement for PRs
- Browse issues labeled **`good first issue`** (newcomer-friendly) or **`help
wanted`** (general contributions).
- For other issues, please kindly ask before contributing to avoid
duplication.
- All PRs, other than small documentation or typo fixes, should have a Issue assoicated. If not, please create one.
- Small, focused PRs. Keep changes minimal—one concern per PR.
- For bug fixes or features, please provide logs or screenshot after the fix is applied to help reviewers better understand the fix.
- Please include a `testing plan` section in your PR to talk about how you will test. This will save time for PR review. See `Testing Requirements` section for more details.
### Requirement for PRs
- All PRs, other than small documentation or typo fixes, should have an Issue
associated. If a relevant issue doesn't exist, please create one first or
you may instead describe the bug or feature directly within the PR
description, following the structure of our issue templates.
- Small, focused PRs. Keep changes minimal—one concern per PR.
- For bug fixes or features, please provide logs or screenshot after the fix
is applied to help reviewers better understand the fix.
- Please include a `testing plan` section in your PR to describe how you
will test. This will save time for PR review. See `Testing Requirements`
section for more details.
### Large or Complex Changes
## Large or Complex Changes
For substantial features or architectural revisions:
- Open an Issue First: Outline your proposal, including design considerations and impact.
- Gather Feedback: Discuss with maintainers and the community to ensure alignment and avoid duplicate work
- Open an Issue First: Outline your proposal, including design considerations
and impact.
- Gather Feedback: Discuss with maintainers and the community to ensure
alignment and avoid duplicate work
## Testing Requirements
### Testing Requirements
To maintain code quality and prevent regressions, all code changes must include comprehensive tests and verifiable end-to-end (E2E) evidence.
To maintain code quality and prevent regressions, all code changes must include
comprehensive tests and verifiable end-to-end (E2E) evidence.
#### Unit Tests
### Unit Tests
Please add or update unit tests for your change. Please include a summary of passed `pytest` results.
Please add or update unit tests for your change. Please include a summary of
passed `pytest` results.
Requirements for unit tests:
- **Coverage:** Cover new features, edge cases, error conditions, and typical use cases.
- **Location:** Add or update tests under `tests/unittests/`, following existing naming conventions (e.g., `test_<module>_<feature>.py`).
- **Framework:** Use `pytest`. Tests should be:
- Fast and isolated.
- Written clearly with descriptive names.
- Free of external dependencies (use mocks or fixtures as needed).
- **Quality:** Aim for high readability and maintainability; include docstrings or comments for complex scenarios.
- **Coverage:** Cover new features, edge cases, error conditions, and typical
use cases.
- **Location:** Add or update tests under `tests/unittests/`, following
- Free of external dependencies (use mocks or fixtures as needed).
- **Quality:** Aim for high readability and maintainability; include
docstrings or comments for complex scenarios.
### Manual End-to-End (E2E) Tests
#### Manual End-to-End (E2E) Tests
Manual E2E tests ensure integrated flows work as intended. Your tests should cover all scenarios. Sometimes, it's also good to ensure relevant functionality is not impacted.
Manual E2E tests ensure integrated flows work as intended. Your tests should
cover all scenarios. Sometimes, it's also good to ensure relevant functionality
is not impacted.
Depending on your change:
- **ADK Web:**
- Use the `adk web` to verify functionality.
- Capture and attach relevant screenshots demonstrating the UI/UX changes or outputs.
- Label screenshots clearly in your PR description.
- **ADK Web:**
- **Runner:**
- Provide the testing setup. For example, the agent definition, and the runner setup.
- Execute the `runner` tool to reproduce workflows.
- Include the command used and console output showing test results.
- Highlight sections of the log that directly relate to your change.
- Use the `adk web` to verify functionality.
- Capture and attach relevant screenshots demonstrating the UI/UX changes
or outputs.
- Label screenshots clearly in your PR description.
## Documentation
- **Runner:**
For any changes that impact user-facing documentation (guides, API reference, tutorials), please open a PR in the [adk-docs](https://github.com/google/adk-docs) repository to update relevant part before or alongside your code PR.
- Provide the testing setup. For example, the agent definition, and the
runner setup.
- Execute the `runner` tool to reproduce workflows.
- Include the command used and console output showing test results.
- Highlight sections of the log that directly relate to your change.
### Documentation
For any changes that impact user-facing documentation (guides, API reference,
tutorials), please open a PR in the
[adk-docs](https://github.com/google/adk-docs) repository to update the relevant
part before or alongside your code PR.
## Development Setup
1. **Clone the repository:**
```shell
@@ -110,11 +140,13 @@ For any changes that impact user-facing documentation (guides, API reference, tu
2. **Install uv:**
Check out [uv installation guide](https://docs.astral.sh/uv/getting-started/installation/).
[](https://github.com/google/adk-python/actions/workflows/python-unit-tests.yml)
Agent Development Kit (ADK) is a flexible and modular framework for developing and deploying AI agents. While optimized for Gemini and the Google ecosystem, ADK is model-agnostic, deployment-agnostic, and is built for compatibility with other frameworks. ADK was designed to make agent development feel more like software development, to make it easier for developers to create, deploy, and orchestrate agentic architectures that range from simple tasks to complex workflows.
Agent Development Kit (ADK) is a flexible and modular framework that applies
software development principles to AI agent creation. It is designed to
simplify building, deploying, and orchestrating agent workflows, from simple
tasks to complex systems. While optimized for Gemini, ADK is model-agnostic,
deployment-agnostic, and compatible with other frameworks.
---
## 🔥 What's new
- **Custom Service Registration**: Add a service registry to provide a generic way to register custom service implementations to be used in FastAPI server. See [short instruction](https://github.com/google/adk-python/discussions/3175#discussioncomment-14745120). ([391628f](https://github.com/google/adk-python/commit/391628fcdc7b950c6835f64ae3ccab197163c990))
- **Rewind**: Add the ability to rewind a session to before a previous invocation ([9dce06f](https://github.com/google/adk-python/commit/9dce06f9b00259ec42241df4f6638955e783a9d1)).
- **New CodeExecutor**: Introduces a new AgentEngineSandboxCodeExecutor class that supports executing agent-generated code using the Vertex AI Code Execution Sandbox API ([ee39a89](https://github.com/google/adk-python/commit/ee39a891106316b790621795b5cc529e89815a98))
- **Tool Confirmation**: A [tool confirmation flow(HITL)](https://google.github.io/adk-docs/tools/confirmation/) that can guard tool execution with explicit confirmation and custom input.
- **Modular Multi-Agent Systems**: Design scalable applications by composing
multiple specialized agents into flexible hierarchies.
- **Deploy Anywhere**: Easily containerize and deploy agents on Cloud Run or
scale seamlessly with Vertex AI Agent Engine.
## 🤖 Agent2Agent (A2A) Protocol and ADK Integration
For remote agent-to-agent communication, ADK integrates with the
Note: The development version is built directly from the latest code commits. While it includes the newest fixes and features, it may also contain experimental changes or bugs not present in the stable release. Use it primarily for testing upcoming changes or accessing critical fixes before they are officially released.
## 🤖 Agent2Agent (A2A) Protocol and ADK Integration
For remote agent-to-agent communication, ADK integrates with the
# Create parent agent and assign children via sub_agents
coordinator=LlmAgent(
name="Coordinator",
model="gemini-2.0-flash",
model="gemini-2.5-flash",
description="I coordinate greetings and tasks.",
sub_agents=[# Assign sub_agents here
greeter,
@@ -138,6 +156,20 @@ We welcome contributions from the community! Whether it's bug reports, feature r
- [General contribution guideline and flow](https://google.github.io/adk-docs/contributing-guide/).
- Then if you want to contribute code, please read [Code Contributing Guidelines](./CONTRIBUTING.md) to get started.
## Community Repo
We have [adk-python-community repo](https://github.com/google/adk-python-community) that is home to a growing ecosystem of community-contributed tools, third-party
service integrations, and deployment scripts that extend the core capabilities
of the ADK.
## Vibe Coding
If you want to develop agent via vibe coding the [llms.txt](./llms.txt) and the [llms-full.txt](./llms-full.txt) can be used as context to LLM. While the former one is a summarized one and the later one has the full information in case your LLM has big enough context window.
## Community Events
- [Completed] ADK's 1st community meeting on Wednesday, October 15, 2025. Remember to [join our group](https://groups.google.com/g/adk-community) to get access to the [recording](https://drive.google.com/file/d/1rpXDq5NSH8-MyMeYI6_5pZ3Lhn0X9BQf/view), and [deck](https://docs.google.com/presentation/d/1_b8LG4xaiadbUUDzyNiapSFyxanc9ZgFdw7JQ6zmZ9Q/edit?slide=id.g384e60cdaca_0_658&resourcekey=0-tjFFv0VBQhpXBPCkZr0NOg#slide=id.g384e60cdaca_0_658).
## 📄 License
This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.