Compare commits

...

1024 Commits

Author SHA1 Message Date
Luke Street 7239de5a19 fix: Address code review feedback for document upload support
- Use startswith() for MIME type check to handle parameters (e.g.
  "application/pdf; name=doc.pdf")
- Move import base64 to top of test file per PEP 8
- Parameterize expected warning messages in tests instead of just
  checking that any warning was logged
- Rename test function to test_content_to_message_param for clarity
2026-03-05 15:10:44 -07:00
Luke Street 8176f30c73 feat: Add PDF document upload support to Anthropic LLM adapter
Adds support for PDF document parts in the Anthropic adapter by converting
inline PDF data to Anthropic's `DocumentBlockParam` format using base64
encoding, matching the existing pattern for image part handling.
2026-03-05 15:04:52 -07:00
Kathy Wu 44a5e6bdb8 feat: Add support for ADK tools in SkillToolset
To use ADK tools, users can specify the tool name in a skill object's `additional_tools` and pass the tool in when initializing a SkillToolset.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 879230409
2026-03-05 13:52:46 -08:00
Haiyuan Cao bcf38fa2ba feat: Enhance BigQuery plugin schema upgrades and error reporting
This change introduces several improvements to the BigQuery Agent Analytics Plugin:

*   **Fix 1 (High):** Error callbacks (`on_model_error_callback`, `on_tool_error_callback`) now emit `status="ERROR"` instead of defaulting to `"OK"`.
*   **Fix 2 (Medium):** Schema upgrade now detects missing sub-fields in nested RECORD columns via a new recursive helper. The version label is now stamped only after the `update_table` call succeeds, ensuring failures can be retried.
*   **Fix 3 (Medium):** Multi-loop `shutdown()` now drains batch processors on non-current event loops using `run_coroutine_threadsafe` before closing transports.
*   **Fix 4 (Medium):** Session state is truncated before logging to prevent oversized payloads.
*   **Fix 5 (Low):** String system prompts are now truncated during content parsing.
*   **Fix 6 (Low):** Removed the unused `_HITL_TOOL_NAMES` frozenset.

Co-authored-by: Haiyuan Cao <haiyuan@google.com>
PiperOrigin-RevId: 879147684
2026-03-05 10:53:14 -08:00
Google Team Member feefadfcc9 ADK changes
PiperOrigin-RevId: 879030011
2026-03-05 06:20:30 -08:00
Achuth Narayan Rajagopal a61ccf36a2 feat(telemetry): add new gen_ai.agent.version span attribute
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:

Problem:
The agent's specific version wasn't being tracked in our telemetry data, limiting our ability to trace issues to specific agent versions. This change introduces the gen_ai.agent.version attribute to span context, defaulting to an empty string if omitted for backwards compatibility.

Solution:
We want to capture the specific version of an agent during execution by adding an optional version field to the base agent configurations (BaseAgent, BaseAgentConfig).

This solution was chosen because exposing this field directly to OpenTelemetry span attributes (gen_ai.agent.version) ensures the version is automatically recorded alongside other existing metadata (like name and description) during invocation. Defaulting the value to an empty string ensures backwards compatibility without breaking existing agent implementations that do not specify a version.

Testing Plan

- Added test_trace_agent_invocation_with_version to verify that the gen_ai.agent.version attribute is correctly captured when agent.version is populated.
- Updated existing telemetry span tests to ensure gen_ai.agent.version safely defaults to an empty string ('') when no version is provided.

Unit Tests:

- I have added or updated unit tests for my change.
- All unit tests pass locally.

Manual End-to-End (E2E) Tests:

- Tested on Agent Engine and in a local deployment.

Checklist
[x] I have read the 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.

Co-authored-by: Achuth Narayan Rajagopal <achuthr@google.com>
PiperOrigin-RevId: 878835568
2026-03-04 22:11:15 -08:00
Google Team Member 36e76b98b3 ADK changes
PiperOrigin-RevId: 878768583
2026-03-04 18:48:47 -08:00
Kathy Wu ab4b9526fc chore: Move spanner tools to integration folder
Added a deprecation warning in the old tools/spanner/__init__.py

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 878742289
2026-03-04 17:24:31 -08:00
Google Team Member 2addf6b9da fix: Fix Type Error by initializing user_content as a Content object
PiperOrigin-RevId: 878682788
2026-03-04 14:59:37 -08:00
Mark Nawar 3b5937f022 fix: filter non-agent directoris from list_agents()
Merge https://github.com/google/adk-python/pull/4648

**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: #4647
- Related: #3429, #3430

**2. Or, if no issue exists, describe the change:**

**Problem:**
`AgentLoader.list_agents()` returns every non-hidden subdirectory in the agents directory, regardless of whether it contains a valid agent definition. This causes non-agent directories (e.g. `tmp/`, `data/`, `utils/`) to appear in the `/list-apps` API response. This affects both the ADK web UI agent selector and any production deployment depending on this API.

**Solution:**
Reuse the existing `_determine_agent_language()` method inside `list_agents()` to verify each candidate directory contains at least one recognized agent file (`root_agent.yaml`, `agent.py`, or `__init__.py`). Directories that fail this check are excluded from the result. This avoids introducing any new methods or abstractions and keeps the check lightweight (filesystem only, no agent imports).

### Testing Plan

**Unit Tests:**

- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.

27 passed in 2.85s:
pytest tests/unittests/cli/utils/test_agent_loader.py -v
======================= 27 passed, 14 warnings in 2.85s ========================

Added `test_list_agents_excludes_non_agent_directories` which creates a temp directory with three valid agent types (package with `__init__.py`, module with `agent.py`, YAML with `root_agent.yaml`) and three non-agent directories, and asserts only the valid agents are listed.

**Screenshots / Video:**
| Before (non-agent directories listed) | After (only valid agents listed) |
|----------------------------------------|----------------------------------|
|<img width="566" height="553" alt="Image" src="https://github.com/user-attachments/assets/0f50084b-319f-480e-8d8a-051c28d4a7e7" />|<img width="567" height="532" alt="Image" src="https://github.com/user-attachments/assets/52d3543f-4c4c-4ff3-a6dd-7d5ce3f19bb2" />|

**Manual End-to-End (E2E) Tests:**

1. Create a project directory containing both valid agent subdirectories and non-agent subdirectories
2. Run `adk web .`
3. Open the web UI and verify only valid agents appear in the agent selector
4. See screenshots below for before/after comparison

### 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

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4648 from markadelnawar:fix/list-agents-filter-non-agents-dirs 041895610fa0c52f2bf3cf7ba0d072a5c580c1b6
PiperOrigin-RevId: 878674609
2026-03-04 14:41:07 -08:00
George Weale 94684874e4 fix: Expand LiteLLM reasoning extraction to include 'reasoning' field
The `_extract_reasoning_value` function now checks for both 'reasoning_content' and 'reasoning' fields in LiteLLM messages, with 'reasoning_content' taking precedence

Close #3694

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 878668213
2026-03-04 14:27:51 -08:00
Xiang (Sean) Zhou c36a708058 fix: Support before_tool_callback and after_tool_callback in Live mode
Close #4704

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 878662637
2026-03-04 14:14:34 -08:00
Kathy Wu 45fb53b9e2 chore: Move API registry to the integrations folder
Added a deprecation warning in the old tools/api_registry file.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 878660213
2026-03-04 14:09:44 -08:00
Google Team Member 34c560e66e feat(bigtable): add Bigtable cluster metadata tools
PiperOrigin-RevId: 878648015
2026-03-04 13:41:54 -08:00
George Weale d0825d817e fix: Change Mypy workflow trigger to manual dispatch
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 878643857
2026-03-04 13:34:13 -08:00
不做了睡大觉 2780ae2892 fix: temp-scoped state now visible to subsequent agents in same invocation
Merge https://github.com/google/adk-python/pull/4618

## Summary

Fixes #4564

When using `output_key` with a `temp:` prefix (e.g. `output_key='temp:result'`) in a `SequentialAgent`, the output was silently lost. Agent-2 could never read the temp state written by agent-1.

## Root Cause

Two issues in `append_event`:

1. `_trim_temp_delta_state()` removed temp keys from the event delta **before** `_update_session_state()` could apply them to the in-memory session
2. `_update_session_state()` also explicitly skipped `temp:`-prefixed keys

```python
# Before (broken ordering):
async def append_event(self, session, event):
    event = self._trim_temp_delta_state(event)   # temp keys gone!
    self._update_session_state(session, event)    # nothing to apply
```

## Fix

Introduce `_apply_temp_state()` which writes temp-scoped keys to the in-memory `session.state` **before** the event delta is trimmed:

```python
# After:
async def append_event(self, session, event):
    self._apply_temp_state(session, event)        # temp keys → session.state
    event = self._trim_temp_delta_state(event)    # temp keys removed from delta
    self._update_session_state(session, event)    # non-temp keys applied
```

This ensures:
-  Temp state is available to subsequent agents within the same invocation
-  Temp state is still stripped from event deltas (not persisted to storage)
-  All three session services (InMemory, Database, SQLite) behave consistently

## Files Changed

- `src/google/adk/sessions/base_session_service.py`: Added `_apply_temp_state()`, reordered `append_event` logic, removed temp-skip in `_update_session_state`
- `src/google/adk/sessions/database_session_service.py`: Added `_apply_temp_state()` call before trim
- `src/google/adk/sessions/sqlite_session_service.py`: Added `_apply_temp_state()` call before trim
- `tests/unittests/sessions/test_session_service.py`: Updated existing test + added new test for sequential agent scenario

## Testing

All 67 session service tests pass across InMemory, Database, and SQLite backends.

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4618 from stakeswky:fix/temp-state-output-key b9fc737e7a6dc07e06e99af3271a8fc026acae4a
PiperOrigin-RevId: 878499263
2026-03-04 08:15:43 -08:00
Google Team Member 6770e419f5 feat: New implementation of RemoteA2aAgent and A2A-ADK conversion
This change introduces compatibility of the remote_a2a_agent with the new a2a_agent_executor.

New Event Converters:
`to_adk_event.py`= Defines a new set of default converters for transforming A2A types (Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent) into ADK Event objects.

Configurable Remote Agent:
The A2aRemoteAgentConfig object allows users to override the default event converters with custom ones.

New AgentExecutor Compatibility:
RemoteA2aAgent now checks for `agent_executor_v2` metadata in A2A responses.
If detected, it delegates response handling to a new `_handle_a2a_response_impl` method, which utilizes the modular converters defined in the configuration.

PiperOrigin-RevId: 878487448
2026-03-04 07:43:41 -08:00
Google Team Member 82c2eefb27 feat: add Dataplex Catalog search tool to BigQuery ADK
Previous rollback CL - cl/872951141

This change introduces a new search_catalog tool within the BigQuery toolset, enabling users to search for BigQuery assets across projects using the Dataplex Catalog API.

Key changes include:
-   Adding google-cloud-dataplex as a dependency in pyproject.toml.
-   Updating BigQuery credentials to include the Dataplex scope.
-   Implementing get_dataplex_catalog_client in client.py to create Dataplex API clients.
-   Creating search_tool.py with the search_catalog function, which constructs and executes Dataplex search queries.
-   Adding extensive unit tests for the new Dataplex client and the search_catalog tool, covering various scenarios including query filtering and error handling.
-   Updating the BigQuery toolset to include the new search_catalog tool.
-   Updating the BigQuery samples README to mention the new tool.

PiperOrigin-RevId: 878435463
2026-03-04 05:20:16 -08:00
Google Team Member 87ffc55640 feat: New implementation of A2aAgentExecutor and A2A-ADK conversion
This change introduces new implementation files for the A2aAgentExecutor and event converters. The existing A2aAgentExecutor now acts as a wrapper, allowing a switch between the legacy and new implementations. The new implementation includes support for execution interceptors and a dedicated executor context.

Main Changes=

`a2a_agent_executor_impl.py` = the new implementation of the AgentExecutor differs from the legacy one (`a2a_agent_executor.py`) for the removal of the TaskResultAggregator and the explicit `InvocationContext` creation. Instead, it uses `ExecutorContext` and delegates event conversion to the new logic that supports streaming. It maintains an `agents_artifact` state map to handle partial updates and emits TaskArtifactUpdateEvents for content. The `long_running_functions.py` is used to keep track of the LongRunning FunctionCalls and respective FunctionResponse, to emit them at the end of the generation loop in a `TaskStateUpdateEvent(input-required/auth-required)`.

`from_adk_event.py` = this file replaces the conversion functions in the `event_converter.py` used to convert the adk events into a2a events, estrapolating them in a dedicated file. The main changes in the methods are the introduction of TaskArtifactUpdateEvent to handle content parts, allowing for true artifact streaming and chunking. It utilizes an `agents_artifacts` dictionary to track artifact IDs across partial events to correctly handle append operations.

PiperOrigin-RevId: 878399140
2026-03-04 03:25:44 -08:00
Bastien Jacot-Guillarmod 2b8ccd4a00 chore: Exclude BaseAgent.parent_agent from serialization
Otherwise, serialization fails due to circular references.

PiperOrigin-RevId: 878339838
2026-03-04 00:43:36 -08:00
Xuan Yang 63f450e023 feat: Support all types.SchemaUnion as output_schema in LLM Agent
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 878194677
2026-03-03 17:18:53 -08:00
George Weale b004da5027 fix: Allow artifact services to accept dictionary representations of types.Part
This change introduces an `ensure_part` helper function that normalizes input to `types.Part`. This allows `save_artifact` methods in `FileArtifactService`, `GcsArtifactService`, and `InMemoryArtifactService` to accept dictionaries, including those with camelCase keys as used by Agentspace, and convert them into proper `types.Part` instances before saving

Close #2886

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 878131948
2026-03-03 14:41:54 -08:00
George Weale 2e434ca7be fix: Store and retrieve EventCompaction via custom_metadata in Vertex AISessionService
This change enables round-tripping of EventCompaction data by storing it within the event's custom_metadata under the key "_compaction" when appending events. When retrieving events, the "_compaction" data is extracted from custom_metadata and used to populate the EventActions.compaction field. This is a temporary measure until the Vertex AI SDK's SessionEvent model supports a dedicated compaction field.

Close #3465

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 878128265
2026-03-03 14:33:25 -08:00
George Weale d61846f6c6 fix: Optimize row-level locking in append_event
Only acquire FOR UPDATE locks on app and user state rows when the event's state_delta contains changes for those specific scopes. This avoids unnecessary locking on state rows that are not being modified, improving concurrency.

Close #4655

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 878108562
2026-03-03 13:45:44 -08:00
Keyur Joshi 4e3e2cb588 feat: Add GEPA root agent prompt optimizer
details:
* Uses GEPA (https://gepa-ai.github.io/gepa/) to optimize the instructions for the root agent. Can be extended to sub-agents and other components in the future.
* GEPA package is imported dynamically; you do not need to install it along with ADK unless you plan to use this optimizer.

Co-authored-by: Keyur Joshi <keyurj@google.com>
PiperOrigin-RevId: 878009649
2026-03-03 10:16:45 -08:00
George Weale 245b2b9874 fix: Add usage field to ModelResponse in LiteLLM tests
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 877954087
2026-03-03 08:13:02 -08:00
Drew Afromsky dd0851ac74 fix: Update expected UsageMetadataChunk in LiteLLM tests
Close #4680

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 877646178
2026-03-02 17:10:43 -08:00
George Weale 5770cd3776 feat: Add streaming support for Anthropic models
Refactor ToolResultBlockParam content handling to use json.dumps for dict/list results.
Implement _generate_content_streaming to handle Anthropic's streaming API

Close #3250

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 877613612
2026-03-02 15:47:59 -08:00
Haiyuan Cao 80c5a24555 feat: Enhance BQ plugin with fork safety, auto views, and trace continuity
- **Fork-safety (#4636):** Adds PID tracking to `BigQueryAgentAnalyticsPlugin` so that forked child processes detect stale gRPC channels and re-initialize instead of deadlocking. Uses the standard `os.getpid()` pattern (same as SQLAlchemy, gRPC-python).
- **Auto-create views (#4639):** After ensuring the `agent_events` table exists, automatically creates 15 per-event-type BigQuery views (`v_llm_request`, `v_tool_completed`, etc.) that unnest JSON columns into typed, queryable columns. Controlled by `BigQueryLoggerConfig.create_views` (default `True`), idempotent via `CREATE OR REPLACE VIEW`.
- **Trace-ID continuity & o11y alignment (#4645):** Fixes trace_id fracture between early events (USER_MESSAGE_RECEIVED, INVOCATION_STARTING) and later events (AGENT_STARTING onwards) when no ambient OTel span exists. Also aligns BQ rows with Cloud Trace span IDs when o11y is active.
- **Span-ID consistency under ambient OTel (#4640 review):** Fixes `*_STARTING` / `*_COMPLETED` events producing mismatched span IDs when an ambient OTel span is active. Completion callbacks now check for ambient spans and defer to `_resolve_ids` Layer 2 instead of overriding with plugin-synthetic IDs.
- **Stack leak safety (#4640 review):** Adds `TraceManager.clear_stack()` and makes `ensure_invocation_span()` clear stale records from *different* invocations, preventing span stack leaks across invocations. Uses `_active_invocation_id_ctx` to distinguish stale leak vs same-invocation re-entry.
- **Root agent name staleness fix:** `init_trace()` now refreshes `_root_agent_name_ctx` unconditionally on each invocation (previously set-once-on-None). `after_run_callback` resets it alongside other invocation cleanup.
- **Exception-safe cleanup:** `after_run_callback` uses `try/finally` to guarantee invocation state (`clear_stack`, `_active_invocation_id_ctx`, `_root_agent_name_ctx`) is always reset, even if `_log_event` raises.
- **`on_tool_error_callback` span fix:** Previously discarded the span_id from `pop_span()`, causing TOOL_ERROR events to get the wrong span. Now captures and uses the popped span_id.

Co-authored-by: Haiyuan Cao <haiyuan@google.com>
PiperOrigin-RevId: 877580395
2026-03-02 14:32:15 -08:00
Xiang (Sean) Zhou c59afc21cb refactor: extract reusable functions from hitl and auth preprocessor
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 877578253
2026-03-02 14:27:27 -08:00
Google Team Member 8e79a12d6b fix: Make invocation_context optional in convert_event_to_a2a_message
PiperOrigin-RevId: 877565033
2026-03-02 13:59:36 -08:00
Google Team Member 72f3e7e1e0 fix: update Bigtable query tools to async functions
PiperOrigin-RevId: 877558234
2026-03-02 13:43:49 -08:00
Xiang (Sean) Zhou b4bad26720 chore: Update pydantic versions
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 877553194
2026-03-02 13:33:15 -08:00
Google Team Member f324fa2d62 fix: Propagate file names during A2A to/from Genai Part conversion
This change updates the part_converter to ensure that the name field in a2a_types.FileWithUri and a2a_types.FileWithBytes is correctly mapped to the display_name field in genai_types.FileData and genai_types.Blob, respectively, during conversions between A2A and Genai Part types. Tests are updated to verify this propagation in both directions.

PiperOrigin-RevId: 877507283
2026-03-02 11:51:12 -08:00
Xuan Yang 90f28deea5 chore: Allow custom parameter names for ToolContext injection
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 877502827
2026-03-02 11:41:29 -08:00
Shruti Nair 9c45166281 feat: execute-type param addition in GkeCodeExecutor
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4111 from SHRUTI6991:execute-type/param-addition b1ec403e0927767d17c11cb9e894f6ccb4f08dd2
PiperOrigin-RevId: 877476098
2026-03-02 10:50:43 -08:00
George Weale 89df5fcf88 feat: Enable output schema with tools for LiteLlm models
LiteLlm provides built-in handling for tool and response format compatibility across different providers, allowing output schemas to be used reliably with tools for any LiteLlm instance

Close #3969

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 877471153
2026-03-02 10:40:16 -08:00
Xuan Yang f9c104faf7 fix: Preserve thought_signature in FunctionCall conversions between GenAI and A2A
Close: https://github.com/google/adk-python/issues/4311

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 877465519
2026-03-02 10:29:06 -08:00
dependabot[bot] a61c7e3880 chore(deps): bump flask from 3.1.1 to 3.1.3 in /contributing/samples/authn-adk-all-in-one in the pip group across 1 directory
Merge https://github.com/google/adk-python/pull/4571

Bumps the pip group with 1 update in the /contributing/samples/authn-adk-all-in-one directory: [flask](https://github.com/pallets/flask).

Updates `flask` from 3.1.1 to 3.1.3
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/pallets/flask/releases">flask's releases</a>.</em></p>
<blockquote>
<h2>3.1.3</h2>
<p>This is the Flask 3.1.3 security fix release, which fixes a security issue but does not otherwise change behavior and should not result in breaking changes compared to the latest feature release.</p>
<p>PyPI: <a href="https://pypi.org/project/Flask/3.1.3/">https://pypi.org/project/Flask/3.1.3/</a>
Changes: <a href="https://flask.palletsprojects.com/page/changes/#version-3-1-3">https://flask.palletsprojects.com/page/changes/#version-3-1-3</a></p>
<ul>
<li>The session is marked as accessed for operations that only access the keys but not the values, such as <code>in</code> and <code>len</code>. <a href="https://github.com/pallets/flask/security/advisories/GHSA-68rp-wp8r-4726">GHSA-68rp-wp8r-4726</a></li>
</ul>
<h2>3.1.2</h2>
<p>This is the Flask 3.1.2 fix release, which fixes bugs but does not otherwise change behavior and should not result in breaking changes compared to the latest feature release.</p>
<p>PyPI: <a href="https://pypi.org/project/Flask/3.1.2/">https://pypi.org/project/Flask/3.1.2/</a>
Changes: <a href="https://flask.palletsprojects.com/page/changes/#version-3-1-2">https://flask.palletsprojects.com/page/changes/#version-3-1-2</a>
Milestone: <a href="https://github.com/pallets/flask/milestone/38?closed=1">https://github.com/pallets/flask/milestone/38?closed=1</a></p>
<ul>
<li><code>stream_with_context</code> does not fail inside async views. <a href="https://redirect.github.com/pallets/flask/issues/5774">#5774</a></li>
<li>When using <code>follow_redirects</code> in the test client, the final state of <code>session</code> is correct. <a href="https://redirect.github.com/pallets/flask/issues/5786">#5786</a></li>
<li>Relax type hint for passing bytes IO to <code>send_file</code>. <a href="https://redirect.github.com/pallets/flask/issues/5776">#5776</a></li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/pallets/flask/blob/main/CHANGES.rst">flask's changelog</a>.</em></p>
<blockquote>
<h2>Version 3.1.3</h2>
<p>Released 2026-02-18</p>
<ul>
<li>The session is marked as accessed for operations that only access the keys
but not the values, such as <code>in</code> and <code>len</code>. :ghsa:<code>68rp-wp8r-4726</code></li>
</ul>
<h2>Version 3.1.2</h2>
<p>Released 2025-08-19</p>
<ul>
<li><code>stream_with_context</code> does not fail inside async views. :issue:<code>5774</code></li>
<li>When using <code>follow_redirects</code> in the test client, the final state
of <code>session</code> is correct. :issue:<code>5786</code></li>
<li>Relax type hint for passing bytes IO to <code>send_file</code>. :issue:<code>5776</code></li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/pallets/flask/commit/22d924701a6ae2e4cd01e9a15bbaf3946094af65"><code>22d9247</code></a> release version 3.1.3</li>
<li><a href="https://github.com/pallets/flask/commit/089cb86dd22bff589a4eafb7ab8e42dc357623b4"><code>089cb86</code></a> Merge commit from fork</li>
<li><a href="https://github.com/pallets/flask/commit/c17f379390731543eea33a570a47bd4ef76a54fa"><code>c17f379</code></a> request context tracks session access</li>
<li><a href="https://github.com/pallets/flask/commit/27be9338405382445a7cb01151e084559b98d602"><code>27be933</code></a> start version 3.1.3</li>
<li><a href="https://github.com/pallets/flask/commit/4e652d3f68b90d50aa2301d3b7e68c3fafd9251d"><code>4e652d3</code></a> Abort if the instance folder cannot be created (<a href="https://redirect.github.com/pallets/flask/issues/5903">#5903</a>)</li>
<li><a href="https://github.com/pallets/flask/commit/3d03098a97ddc6a908aa4a50c2ef7381f8297d0a"><code>3d03098</code></a> Abort if the instance folder cannot be created</li>
<li><a href="https://github.com/pallets/flask/commit/407eb76b27884848383a37c7274654f0271e4bc4"><code>407eb76</code></a> document using gevent for async (<a href="https://redirect.github.com/pallets/flask/issues/5900">#5900</a>)</li>
<li><a href="https://github.com/pallets/flask/commit/ac5664d2281533eacafd64f5cc7d5edcdaccab60"><code>ac5664d</code></a> document using gevent for async</li>
<li><a href="https://github.com/pallets/flask/commit/4f79d5b59a56bc4356a97f2e81a35f98cb18d7b3"><code>4f79d5b</code></a> Increase required flit_core version to 3.11 (<a href="https://redirect.github.com/pallets/flask/issues/5865">#5865</a>)</li>
<li><a href="https://github.com/pallets/flask/commit/fe3b215d3ade4db68262dae1a3cdc464a1fc524f"><code>fe3b215</code></a> Increase required flit_core version to 3.11</li>
<li>Additional commits viewable in <a href="https://github.com/pallets/flask/compare/3.1.1...3.1.3">compare view</a></li>
</ul>
</details>
<br />

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=flask&package-manager=pip&previous-version=3.1.1&new-version=3.1.3)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will remove the ignore condition of the specified dependency and ignore conditions
You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/google/adk-python/network/alerts).

</details>

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4571 from google:dependabot/pip/contributing/samples/authn-adk-all-in-one/pip-81068183c6 6f577df16cb78beec2d26d873761173811f6ef5b
PiperOrigin-RevId: 877461954
2026-03-02 10:21:29 -08:00
George Weale 6a929af718 fix: Prevent splitting of SSE events with artifactDelta for function resume requests
When handling a /run_sse request that includes a functionCallEventId, do not split events that contain both content and artifactDelta

Close #4487

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 877435561
2026-03-02 09:25:22 -08:00
nikkie 991abd44e9 chore: escape Click's wrapping
Escape Click’s Wrapping in `adk deploy agent_engine` example

Merge https://github.com/google/adk-python/pull/4337

### Link to Issue or Description of Change

**2. Or, if no issue exists, describe the change:**

**Problem:**
`adk deploy agent_engine` help message loses newlines in docstring formatting

<img width="749" height="257" alt="スクリーンショット 2026-01-31 13 29 18" src="https://github.com/user-attachments/assets/ede7d9e7-609d-4412-acce-c80e24ec1e2f" />

**Solution:**

Add `\b` on a line by itself before the formatted block

### Testing Plan

This is format improvement of help message, so I think there is no need to add test case.

**Unit Tests:**

- [ ] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.

```
% pytest tests/unittests/cli  # Python 3.13.8
======================= 260 passed, 140 warnings in 7.73s ========================
```

**Manual End-to-End (E2E) Tests:**

Ran `adk deploy agent_engine --help`, then saw

```
  Example:

      # With Express Mode API Key
      adk deploy agent_engine --api_key=[api_key] my_agent

      # With Google Cloud Project and Region
      adk deploy agent_engine --project=[project] --region=[region]
        --display_name=[app_name] my_agent
```

### 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

Same solution as #4258

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4337 from ftnext:escape-wrapping-deploy-agent-engine-example 09440380dd5b1e14a48151eba1b808def8ae3b6a
PiperOrigin-RevId: 877205878
2026-03-01 22:32:15 -08:00
nikkie eb55eb7e7f fix: typo in A2A EXPERIMENTAL warning
Merge https://github.com/google/adk-python/pull/4462

**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:**
I found a typo: arethemselves

>/.../adk-python/src/google/adk/a2a/converters/event_converter.py:245: UserWarning: [EXPERIMENTAL] convert_a2a_message_to_event: ADK Implementation for A2A support (A2aAgentExecutor, RemoteA2aAgent and corresponding supporting components etc.) is in experimental mode and is subjected to breaking changes. A2A protocol and SDK arethemselves not experimental. Once it's stable enough the experimental mode will be removed. Your feedback is welcome.

**Solution:**
Just fix

### Testing Plan

This is typo fix

**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.
- [ ] 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/4462 from ftnext:fix-typo-a2a-experimental-warning a117314eb524dd93351e17f2183eea080225e43e
PiperOrigin-RevId: 877095788
2026-03-01 14:52:34 -08:00
Shangjie Chen 8ddddc040c chore: Use factory method to create invocation context in the runner
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 876474267
2026-02-27 17:12:06 -08:00
Lusha Wang dff4c44040 fix: Update agent_engine_sandbox_code_executor in ADK
1. For prototyping and testing purposes, sandbox name can be provided, and it will be used for all requests across the lifecycle of an agent
2. If no sandbox name is provided, agent engine name will be provided, and we will automatically create one sandbox per session, and the sandbox has TTL set for a year.
If the sandbox stored in the session hits the TTL, it will not be in "STATE_RUNNING" so a new sandbox will be created.

Co-authored-by: Lusha Wang <lusha@google.com>
PiperOrigin-RevId: 876450610
2026-02-27 15:59:20 -08:00
Wei (Jack) Sun 1206addd6e chore: merge release v1.26.0 to main
Merge https://github.com/google/adk-python/pull/4637

Syncs version bump and CHANGELOG from release v1.26.0 to main.

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4637 from google:release/v1.26.0 427a983b18088bdc22272d02714393b0a779ecdf
PiperOrigin-RevId: 875930970
2026-02-26 16:00:38 -08:00
Kathy Wu 8ad8bc9b69 fix: Add a script to the sample skills agent
Added a get_humidity script to demo the new RunSkillScript tool

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 875901416
2026-02-26 14:50:02 -08:00
Ke Wang 8a3161202e feat(skill): Add BashTool
PiperOrigin-RevId: 875899505
2026-02-26 14:46:16 -08:00
George Weale ebbc114786 fix: Validate session before streaming instead of eagerly advancing the runner generator
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 875892569
2026-02-26 14:30:42 -08:00
Xuan Yang d55afede1b chore: Stop auto-triggering Release Please after cherry-picks
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 875867583
2026-02-26 13:33:37 -08:00
Kathy Wu b4610fe1c6 chore: Add README for integrations folder
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 875836816
2026-02-26 12:24:24 -08:00
Keyur Joshi 7b7ddda46c feat: Add interface between optimization infra and LocalEvalService
details:
* Enables the use of ADK evaluations via LocalEvalService for optimizing agents.
* Provides flexibility in choosing eval sets and eval cases for training and validation.
* Converts ADK eval results into a compact format useful for whitebox agent optimization.

Co-authored-by: Keyur Joshi <keyurj@google.com>
PiperOrigin-RevId: 875818012
2026-02-26 11:40:37 -08:00
Carlos Chinchilla Corbacho 65d9a726c5 chore: add @override decorators to LoggingPlugin callback methods
Merge https://github.com/google/adk-python/pull/4572

### Link to Issue or Description of Change
**1. Link to an existing issue (if applicable):**
- Closes: #4496

**2. Or, if no issue exists, describe the change:**

**Problem:**

`LoggingPlugin` overrides 12 callback methods from `BasePlugin` but none use the `@override` decorator. Every other plugin in the package (`DebugLoggingPlugin`, `ReplayPlugin`, `RecordingsPlugin`, `EnsureRetryOptionsPlugin`, `_RequestIntercepterPlugin`) already follows this practice. With `mypy --strict` enabled in `pyproject.toml`, missing `@override` means renamed or removed base-class methods would be silently missed in `LoggingPlugin` while being caught everywhere else.

**Solution:**

Import `override` from `typing_extensions` and decorate all 12 overridden callbacks. Purely additive: one import line and 12 decorators. No behavioral, API, or runtime change.

### Testing Plan

**Unit Tests:**
- [ ] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.

No new tests are required — `@override` is a static-analysis-only decorator with no runtime effect. Ran `mypy` on the file before and after the change: same preexisting warnings, no new errors introduced. CI will validate via the existing test suite and linting checks.

**Manual End-to-End (E2E) Tests:**

Not applicable. This change adds only decorators with no runtime behavior. Verified by comparing `mypy` output before and after — no new errors.

### 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.
- [ ] I have manually tested my changes end-to-end.
- [ ] Any dependent changes have been merged and published in downstream modules.

### Additional context

I am the author of the original issue (#4496). A previous PR (#4544) was opened but is pending clarification, so I'm
submitting this complete PR as the original issue author.

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4572 from cchinchilla-dev:feat/add_override_decorators_to_loggingplugin_4496 142ed872bee39db782c1dccb84f40906ee849bb8
PiperOrigin-RevId: 875811966
2026-02-26 11:29:52 -08:00
Wiktoria Walczak 4dd4d5ecb6 feat(otel): add gen_ai.tool.definitions to experimental semconv
Co-authored-by: Wiktoria Walczak <wwalczak@google.com>
PiperOrigin-RevId: 875741416
2026-02-26 08:42:50 -08:00
Google Admin 7a813b0987 chore: refactor Github Action
Co-authored-by: Sasha Sobran <asobran@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4535 from google:lsc-1771431513.0644026 200d04544fafa4c555f2031f66ef6a3c2ff8a774
PiperOrigin-RevId: 875727295
2026-02-26 08:06:59 -08:00
Sasha Sobran b38b708e23 chore: Update release-please to always bump minor
Co-authored-by: Sasha Sobran <asobran@google.com>
PiperOrigin-RevId: 875727292
2026-02-26 08:06:15 -08:00
Wiktoria Walczak 19718e9c17 feat(otel): add experimental semantic convention and emit gen_ai.client.inference.operation.details event
Co-authored-by: Wiktoria Walczak <wwalczak@google.com>
PiperOrigin-RevId: 875709959
2026-02-26 07:19:15 -08:00
Google Team Member 6f772d2b08 feat: Introduce A2A request interceptors in RemoteA2aAgent
This change adds a new `a2a` subpackage with configuration and utility functions for intercepting requests and responses in `RemoteA2aAgent`. The `RemoteA2aAgent` now accepts an `A2aRemoteAgentConfig` to register `RequestInterceptor` instances, allowing custom logic to be executed before and after the A2A message send.

PiperOrigin-RevId: 875559286
2026-02-26 00:23:01 -08:00
Shangjie Chen 5f806ed73a chore: Refactor runner to infer invocation_id from FunctionResponse Event for HITL resuming
invocation_id is no longer required in resuming case, unless no new_message is provided.

Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 875432024
2026-02-25 18:27:16 -08:00
Kathy Wu de4dee899c fix: Re-export DEFAULT_SKILL_SYSTEM_INSTRUCTION to skills and skill/prompt.py to avoid breaking current users
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 875407169
2026-02-25 17:18:29 -08:00
Google Team Member 5702a4b1f5 feat: Add param support to Bigtable execute_sql
PiperOrigin-RevId: 875382675
2026-02-25 16:11:44 -08:00
Google Admin 9730bc34d7 Refactor Github Action per b/485167538 (#4535)
Co-authored-by: Ben Knutson <benknutson@google.com>
2026-02-25 17:09:43 -05:00
Yifan Wang 4460f4fada chore: add /dev/build_graph/{app_name} to build the graph serialization for apps, and
make it dev only with `with_ui` flag

Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 875319398
2026-02-25 13:47:41 -08:00
Google Team Member d7cfd8fe4d fix: Decode image data from ComputerUse tool response into image blobs
PiperOrigin-RevId: 875292001
2026-02-25 12:46:19 -08:00
Haiyuan Cao 35366f4e2a feat: Warn when accessing DEFAULT_SKILL_SYSTEM_INSTRUCTION
This change makes DEFAULT_SKILL_SYSTEM_INSTRUCTION raise a UserWarning when accessed, indicating that its content is experimental and subject to change in minor/patch releases. The constant is also made "private" internally.

Co-authored-by: Haiyuan Cao <haiyuan@google.com>
PiperOrigin-RevId: 875288217
2026-02-25 12:37:30 -08:00
Brian Fox 3256a679da fix(tools): Handle JSON Schema boolean schemas in Gemini schema conversion
Merge https://github.com/google/adk-python/pull/4531

**Problem:**
JSON Schema allows `true` and `false` as valid boolean schemas, where `true` accepts any value and `false` rejects all values. Some MCP servers  use this pattern for unconstrained fields. E.g. [mcp-grafana](https://github.com/grafana/mcp-grafana) - see [grafana-mcp-list-tools.json](https://github.com/user-attachments/files/25392430/grafana-mcp-list-tools.json) which was obtained from `tools/list`

The schema sanitizer previously passed booleans through unchanged, causing a Pydantic ValidationError when `_ExtendedJSONSchema` tried to validate them as schema objects.

```
1 validation error for _ExtendedJSONSchema
properties.data.items.properties.model
  Input should be a valid dictionary or object to extract fields from [type=model_attributes_type, input_value=True, input_type=bool]
    For further information visit https://errors.pydantic.dev/2.12/v/model_attributes_type
Traceback (most recent call last):
  ...
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/runners.py", line 561, in run_async
    async for event in agen:
      yield event
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/runners.py", line 549, in _run_with_trace
    async for event in agen:
      yield event
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/runners.py", line 778, in _exec_with_plugin
    async for event in agen:
    ...<64 lines>...
        yield event
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/runners.py", line 538, in execute
    async for event in agen:
      yield event
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/agents/base_agent.py", line 294, in run_async
    async for event in agen:
      yield event
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/agents/llm_agent.py", line 468, in _run_async_impl
    async for event in agen:
    ...<5 lines>...
        should_pause = True
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/flows/llm_flows/base_llm_flow.py", line 427, in run_async
    async for event in agen:
      last_event = event
      yield event
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/flows/llm_flows/base_llm_flow.py", line 446, in _run_one_step_async
    async for event in agen:
      yield event
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/flows/llm_flows/base_llm_flow.py", line 578, in _preprocess_async
    await tool.process_llm_request(
        tool_context=tool_context, llm_request=llm_request
    )
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/tools/base_tool.py", line 129, in process_llm_request
    llm_request.append_tools([self])
    ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/models/llm_request.py", line 255, in append_tools
    declaration = tool._get_declaration()
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/tools/mcp_tool/mcp_tool.py", line 200, in _get_declaration
    parameters = _to_gemini_schema(input_schema)
  File "/.foo/.venv/lib/python3.13/site-packages/google/adk/tools/_gemini_schema_util.py", line 218, in _to_gemini_schema
    json_schema=_ExtendedJSONSchema.model_validate(sanitized_schema),
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
  File "/.foo/.venv/lib/python3.13/site-packages/pydantic/main.py", line 716, in model_validate
    return cls.__pydantic_validator__.validate_python(
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        obj,
        ^^^^
    ...<5 lines>...
        by_name=by_name,
        ^^^^^^^^^^^^^^^^
    )
    ^
pydantic_core._pydantic_core.ValidationError: 1 validation error for _ExtendedJSONSchema
properties.data.items.properties.model
  Input should be a valid dictionary or object to extract fields from [type=model_attributes_type, input_value=True, input_type=bool]
    For further information visit https://errors.pydantic.dev/2.12/v/model_attributes_type
```

**Solution:**

Convert boolean schemas to `{"type": "object"}` as the closest approximation available in Gemini's schema model.

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4531 from onematchfox:fix-gemini-schema-bool 383ac0c0c3ab78d77be4503f5d6b9ad26c41b0db
PiperOrigin-RevId: 875219362
2026-02-25 10:10:41 -08:00
Google Team Member e59929e11a fix: Propagate thought from A2A TextPart metadata to GenAI Part
When converting an A2A TextPart to a GenAI Part, extract the 'thought' field from the TextPart's metadata and include it in the GenAI Part.

PiperOrigin-RevId: 875129430
2026-02-25 06:23:18 -08:00
Haiyuan Cao 636f68fbee feat: Add RunSkillScriptTool to SkillToolset
Introduces RunSkillScriptTool to execute scripts located in a skill's scripts/ directory.

The execution logic is isolated within a dedicated SkillScriptCodeExecutor wrapper instantiated by RunSkillScriptTool. This wrapper manages script materialization in a temporary directory and executes Python (via runpy) or Shell scripts (returning standard output or JSON-encoded envelopes).

This isolation eliminates the need to modify the underlying `BaseCodeExecutor` interface or implementations (`unsafe_local_code_executor`, etc.) to support working directories or file paths.

Co-authored-by: Haiyuan Cao <haiyuan@google.com>
PiperOrigin-RevId: 875012237
2026-02-25 00:59:01 -08:00
Xuan Yang e4d9540ce3 chore: Make Release: Please workflow only run via workflow_dispatch
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 874980878
2026-02-24 23:29:40 -08:00
Kathy Wu 8f5428150d fix: Update sample skills agent to use weather-skill instead of weather_skill
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 874796345
2026-02-24 14:35:11 -08:00
Google Team Member 121d277416 feat: Add /chat/completions streaming support to Apigee LLM
PiperOrigin-RevId: 874764985
2026-02-24 13:26:43 -08:00
Google Team Member 48105b49c5 fix: Add support for injecting a custom google.genai.Client into Gemini models
This change introduces a new `client` parameter to the `Gemini` model's constructor. When provided, this preconfigured `google.genai.Client` instance is used for all API calls, offering fine-grained control over authentication, project, and location settings

Close #2560

PiperOrigin-RevId: 874752355
2026-02-24 12:58:28 -08:00
Google Team Member ee8d956413 fix: Update agent_engine_sandbox_code_executor in ADK
1. For prototyping and testing purposes, sandbox name can be provided, and it will be used for all requests across the lifecycle of an agent
2. If no sandbox name is provided, agent engine name will be provided, and we will automatically create one sandbox per session, and the sandbox has TTL set for a year.
If the sandbox stored in the session hits the TTL, it will not be in "STATE_RUNNING" so a new sandbox will be created.

PiperOrigin-RevId: 874705260
2026-02-24 11:16:04 -08:00
George Weale 7be90db24b feat: Support ID token exchange in ServiceAccountCredentialExchanger
Adds use_id_token and audience fields to ServiceAccount so that
ServiceAccountCredentialExchanger can produce ID tokens instead of
access tokens. This is required for authenticating to Cloud Run, Cloud
Functions, and other Google Cloud services that verify caller identity.
Close #4458

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 874630210
2026-02-24 08:39:03 -08:00
George Weale c615757ba1 fix: Add support for injecting a custom google.genai.Client into Gemini models
This change introduces a new `client` parameter to the `Gemini` model's constructor. When provided, this preconfigured `google.genai.Client` instance is used for all API calls, offering fine-grained control over authentication, project, and location settings

Close #2560

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 874628604
2026-02-24 08:34:32 -08:00
Sasha Sobran 8c0bd2034c chore: SessionNotFoundError only inherits form ValueError
Co-authored-by: Sasha Sobran <asobran@google.com>
PiperOrigin-RevId: 874545504
2026-02-24 04:42:24 -08:00
Lusha Wang dab80e4a8f fix: Update agent_engine_sandbox_code_executor in ADK
1. For prototyping and testing purposes, sandbox name can be provided, and it will be used for all requests across the lifecycle of an agent
2. If no sandbox name is provided, agent engine name will be provided, and we will automatically create one sandbox per session, and the sandbox has TTL set for a year.
If the sandbox stored in the session hits the TTL, it will not be in "STATE_RUNNING" so a new sandbox will be created.

Co-authored-by: Lusha Wang <lusha@google.com>
PiperOrigin-RevId: 874415933
2026-02-23 23:52:09 -08:00
Google Team Member 6d53d800d5 fix: fix typo in PlanReActPlanner instruction
PiperOrigin-RevId: 874391350
2026-02-23 22:55:50 -08:00
Google Team Member 1dbceccf36 fix: update Spanner query tools to async functions
PiperOrigin-RevId: 874318392
2026-02-23 18:46:37 -08:00
Kathy Wu 37d52b4caf fix: edit copybara and BUILD config for new adk/integrations folder (added with Agent Registry)
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 874293428
2026-02-23 17:15:47 -08:00
Kathy Wu c33d614004 feat: Update Agent Registry to create AgentCard from info in get agents endpoint
Get agents API design is being updated to return full AgentCard instead of agent card url - while it's being rolled out, update get agents method to instantiate agent card from existing fields.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 874285065
2026-02-23 16:44:48 -08:00
Sasha Sobran 445dc189e9 fix: remove duplicate session GET when using API server, unbreak auto_session_create when using API server
Co-authored-by: Sasha Sobran <asobran@google.com>
PiperOrigin-RevId: 874188082
2026-02-23 12:01:24 -08:00
George Weale 2dbd1f25bd fix: Add OpenAI strict JSON schema enforcement in LiteLLM
This change introduces a recursive function to transform JSON schemas to meet OpenAI's strict mode requirements, including adding "additionalProperties: false" to all object schemas, making all properties required, and stripping sibling keywords from $ref nodes. The schema conversion uses deep copies to not mutating the original input

Close #4573

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 874174994
2026-02-23 11:35:35 -08:00
Google Team Member b1e33a90b4 fix: use correct msg_out/msg_err keys for Agent Engine sandbox output
PiperOrigin-RevId: 874126181
2026-02-23 09:56:49 -08:00
George Weale 4ca904f111 fix: Add push notification config store to agent_to_a2a
This change allows users to provide a custom PushNotificationConfigStore when converting an ADK agent to an A2A Starlette application. If no custom store is provided, an InMemoryPushNotificationConfigStore is used by default, thios now lets A2A push notification configuration RPCs

Close #4126

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 874118109
2026-02-23 09:41:16 -08:00
George Weale ffbcc0a626 fix: Keep query params embedded in OpenAPI paths when using httpx
The migration from requests to httpx in v1.24.0 broke ApplicationIntegrationToolset because httpx replaces the URL query string when a `params` dict is passed, even if empty. The requests library merged them instead. This extracts any query parameters embedded in the URL path into the explicit params dict before passing to httpx.

Close #4555

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 874112143
2026-02-23 09:29:22 -08:00
Google Team Member 87fcd77caa feat: Add interceptor framework to A2aAgentExecutor
This change introduces an interceptor mechanism allowing custom logic to be executed before agent runs, after each event, and after the agent run completes. New dependencies are added to support these features.

PiperOrigin-RevId: 873952199
2026-02-23 02:15:41 -08:00
Haiyuan Cao 7557a92939 feat: change default BigQuery table ID and update docstring
The default table ID for the BigQueryAgentAnalyticsPlugin is changed from "agent_events_v2" to "agent_events". The class docstring is also updated to remove the "v2.0" reference.

Co-authored-by: Haiyuan Cao <haiyuan@google.com>
PiperOrigin-RevId: 873485931
2026-02-21 19:04:33 -08:00
Haiyuan Cao 223d9a7ff5 feat: Agent Skills spec compliance — validation, aliases, scripts, and auto-injection
Close gaps between ADK's Agent Skills implementation and the public
Agent Skills spec (agentskills.io/specification):

- Frontmatter: add field validators for name (kebab-case, max 64),
  description (non-empty, max 1024), compatibility (max 500);
  add allowed-tools alias; add extra='allow'; add populate_by_name
- utils: extract _parse_skill_md helper; use model_validate() for
  alias support; enforce name-dir matching; add validate_skill_dir()
  and read_skill_properties()
- prompt: accept Union[Frontmatter, Skill];
- skill_toolset: add scripts/ resource loading; auto-inject system
  instruction (with inject_instruction opt-out); duplicate name check;
  _list_skills() returns Skill objects
- sample agent: remove manual instruction (auto-injected now)

Co-authored-by: Haiyuan Cao <haiyuan@google.com>
PiperOrigin-RevId: 873177060
2026-02-20 19:56:43 -08:00
Haiyuan Cao 4260ef0c7c feat: Add schema auto-upgrade, tool provenance, HITL tracing, and span hierarchy fix to BigQuery Agent Analytics plugin
This CL adds four enhancements to the BigQuery Agent Analytics plugin and fixes a span hierarchy corruption bug.

- **Schema Auto-Upgrade:** Additive-only schema migration that automatically adds missing columns to existing BQ tables on startup. A `adk_schema_version` label on the table (starting at `"1"`, bumped with each schema change) makes the check idempotent — the diff runs at most once per version. Enabled by default (`auto_schema_upgrade=True`) because upgrades are additive-only and fail-safe. Pre-versioning tables (no label) are treated as outdated, diffed, and stamped. No previous schema versions need to be stored; the logic diffs actual columns against the current canonical schema.

- **Tool Provenance:** Adds `tool_origin` to TOOL_* event content, distinguishing six origin types — `LOCAL` (FunctionTool), `MCP` (McpTool), `A2A` (AgentTool wrapping RemoteA2aAgent), `SUB_AGENT` (AgentTool), `TRANSFER_AGENT` (TransferToAgentTool), and `UNKNOWN` (fallback) — via `isinstance()` checks with lazy imports to avoid circular dependencies.

- **HITL Tracing:** Emits dedicated HITL event types (`HITL_CONFIRMATION_REQUEST`, `HITL_CREDENTIAL_REQUEST`, `HITL_INPUT_REQUEST` + `_COMPLETED` variants) for human-in-the-loop interactions. Detection lives in `on_event_callback` (for synthetic `adk_request_*` FunctionCall events emitted by the framework) and `on_user_message_callback` (for `adk_request_*` FunctionResponse completions sent by the user), not in tool callbacks — because `adk_request_*` names are synthetic function calls that bypass `before_tool_callback`/`after_tool_callback` entirely.

- **Span Hierarchy Fix (#4561):** Removes `context.attach()`/`context.detach()` calls from `TraceManager.push_span()`, `attach_current_span()`, and `pop_span()`. The plugin was injecting its spans into the shared OTel context, which corrupted the framework's span hierarchy when an external exporter (e.g. `opentelemetry-instrumentation-vertexai`) was active — causing `call_llm` to be re-parented under `llm_request` and parent spans to show shorter durations than children. The plugin now tracks span_id/parent_span_id via its internal contextvar stack without mutating ambient OTel context.

Co-authored-by: Haiyuan Cao <haiyuan@google.com>
PiperOrigin-RevId: 873114688
2026-02-20 16:13:19 -08:00
George Weale e8019b1b1b fix: Refactor LiteLLM streaming response parsing for compatibility with LiteLLM 1.81+
Updates _model_response_to_chunk to better handle LiteLLM's streaming delta/message structure, including prioritizing delta when it contains meaningful content and preserving reasoning_content

Close #4225

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 873097502
2026-02-20 15:24:29 -08:00
Xuan Yang 6ea3696bcc chore: Migrate /agents to use the new feature decorator
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 873097395
2026-02-20 15:23:34 -08:00
George Weale 485fcb84e3 feat: Add intra-invocation compaction and token compaction pre-request
Compact session events before LLM calls when token threshold is exceeded

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 873095899
2026-02-20 15:19:45 -08:00
George Weale bbdf0ea257 chore: Update OpenTelemetry dependency upper bounds
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 873080640
2026-02-20 14:42:00 -08:00
Kathy Wu abaa92944c feat: Agent Registry in ADK
Client library for the Agent Registry API that allows users to discover, look up, and connect to agents and MCP servers cataloged in the registry.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 873073675
2026-02-20 14:25:08 -08:00
Liang Wu 77df6d8db7 ci: only keep --extra test in GitHub unit test workflow
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 873072872
2026-02-20 14:22:43 -08:00
Google Team Member 9c4c445369 feat: Add /chat/completions integration to ApigeeLlm
PiperOrigin-RevId: 873049983
2026-02-20 13:27:22 -08:00
Google Team Member 09ee3c3695 ADK changes
PiperOrigin-RevId: 873013637
2026-02-20 11:59:54 -08:00
George Weale a7b509763c feat: Use --memory_service_uri in ADK CLI run command
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 873000092
2026-02-20 11:29:02 -08:00
George Weale e6b601a2ab fix: Invoke on_tool_error_callback for missing tools in live mode
In live mode, when the model calls an unregistered tool, ADK now runs on_tool_error_callback before failing. If the callback returns a response, ADK emits
that function response and continues; otherwise it keeps the old ValueError

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 872996178
2026-02-20 11:20:51 -08:00
Kathy Wu 7478bdaa98 fix: Parallelize tool resolution in LlmAgent.canonical_tools()
Previously we resolved tools sequentially by awaiting _convert_tool_union_to_tools() in a loop -- reduce the latency by resolving tools concurrently.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 872979105
2026-02-20 10:45:18 -08:00
Sahaja Reddy Pabbathi Reddy bef3f117b4 feat: Bigquery ADK support for search catalog tool
Merge https://github.com/google/adk-python/pull/4171

**Problem:**
The BigQuery ADK tools currently lack the ability to search for and discover BigQuery assets using the Dataplex Catalog. Users cannot leverage Dataplex's search capabilities within the ADK to find relevant data assets before querying them.

**Solution:**
This PR integrates a new search_catalog_tool into the BigQuery ADK. This tool utilizes the dataplex catalog client library to interact with the Dataplex API, allowing users to search the catalog.

**Unit Tests:**

- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.

Added the screenshots of the manual adk web UI tests - https://docs.google.com/document/d/1c_lMW7NYGKuLAvPFmSkLehbqySeNyXQIhzQlvo3ixmQ/edit?usp=sharing

### 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/4171 from sahaajaaa:sahaajaaa-bq-adk 3dbbaa4f909cb25259e8e7d73a00a58fbe9c2f09
PiperOrigin-RevId: 872951141
2026-02-20 09:55:29 -08:00
George Weale a39ca946d6 chore: Add sqlite_span_exporter for .adk folder traces
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 872948208
2026-02-20 09:49:38 -08:00
George Weale 4a88804ec7 feat: Add support for memory consolidation via Vertex AI Memory Bank
This change allows `add_memory` to use the `memories.generate` API with `direct_memories_source` when `custom_metadata["enable_consolidation"]` is set to True. This enables server-side consolidation of the provided memories

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 872554004
2026-02-19 13:59:31 -08:00
George Weale eaf50ce37e chore: provide a way to disable model check for builtin tools
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 872503435
2026-02-19 12:02:27 -08:00
George Weale f27a9cfb87 fix: Expand add_memory to accept MemoryEntry
The `add_memory` methods in `Context` and `BaseMemoryService` now accept `MemoryEntry` objects in addition to strings. The Vertex AI Memory Bank service implementation is updated to handle these new types

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 872108561
2026-02-18 17:06:17 -08:00
Xiang (Sean) Zhou 2d8b6a2f5b chore: Release 1.25.1
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 872062719
2026-02-18 15:12:50 -08:00
Google Team Member eccdf6d01e fix: Remove experimental decorators from user persona data models
PiperOrigin-RevId: 872026960
2026-02-18 13:50:47 -08:00
Wei Sun (Jack) 710d9de011 chore(release): Update release process to allow tag to use accurate commit sha in the branch
* use last-release-sha to locate the previous release commit in main for CHANGELOG generating.
* release tag can now use the commit sha in release branch

Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 871909085
2026-02-18 09:30:33 -08:00
Google Team Member 33f7d118b3 feat(auth): Add native support for id_token in OAuth2 credentials
## Problem
When performing authentication flows via `OAUTH2` or `OPEN_ID_CONNECT`, the native `OAuth2Token` response from identity providers, like Google OAuth, often includes an `id_token` alongside the `access_token` and `refresh_token`. [MCP Toolbox](https://googleapis.github.io/genai-toolbox/resources/authservices/google/) implements authentication through ID Tokens and [integrates with ADK](https://google.github.io/adk-docs/integrations/mcp-toolbox-for-databases/) to provide easy tools management for the end-users.

However, the ADK's `update_credential_with_tokens` utility explicitly drops the `id_token`, preventing agents and tools from verifying user identity or extracting OIDC claims securely. Furthermore, the `OAuth2Auth` model does not have a designated field for `id_token`.

## Solution
1. Added an `id_token: Optional[str] = None` field to the `OAuth2Auth` pydantic model in `auth_credential.py`.
2. Updated `update_credential_with_tokens` in `oauth2_credential_util.py` to correctly extract and map `tokens.get("id_token")` into the `OAuth2Auth` credential object.
3. Updated the relevant unit tests to ensure `id_token` is asserted and preserved during credential updates.

### Testing Plan

- I have added or updated unit tests for my change.
- All unit tests pass locally.

PiperOrigin-RevId: 871801313
2026-02-18 04:34:39 -08:00
Google Team Member 6a53f414d3 chore: set a maximum number of rows for BigQuery query results in the sample agent
The `BigQueryToolConfig` now sets `max_query_result_rows=50` explicitly to showcase this particular configuration.

PiperOrigin-RevId: 871709345
2026-02-18 00:24:26 -08:00
Wei Sun (Jack) dbd64207ae fix(deps): Increase pydantic lower version to 2.7.0
```
  ┌──────────────────────────────┬─────────────────┬───────────────────────────────────────────────┐
  │           Feature            │ First Available │                    Used In                    │
  ├──────────────────────────────┼─────────────────┼───────────────────────────────────────────────┤
  │ SkipJsonSchema               │ 2.1.0           │ evaluation/eval_metrics.py                    │
  ├──────────────────────────────┼─────────────────┼───────────────────────────────────────────────┤
  │ AliasChoices                 │ 2.1.0           │ models/gemma_llm.py                           │
  ├──────────────────────────────┼─────────────────┼───────────────────────────────────────────────┤
  │ SerializeAsAny               │ 2.1.0           │ agents/workflow/workflow_graph.py             │
  ├──────────────────────────────┼─────────────────┼───────────────────────────────────────────────┤
  │ Discriminator, Tag           │ 2.5.0           │ agents/agent_config.py                        │
  ├──────────────────────────────┼─────────────────┼───────────────────────────────────────────────┤
  │ ser_json_bytes in ConfigDict │ 2.5.0           │ events/event.py, agents/live_request_queue.py │
  ├──────────────────────────────┼─────────────────┼───────────────────────────────────────────────┤
  │ Field(deprecated=True)       │ 2.7.0           │ agents/run_config.py                          │
  └──────────────────────────────┴─────────────────┴───────────────────────────────────────────────┘
```

Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 871478269
2026-02-17 13:47:26 -08:00
Google Team Member 2703613572 fix: Replace the global DEFAULT_USER_PERSONA_REGISTRY with a function call to get_default_persona_registry
PiperOrigin-RevId: 871422993
2026-02-17 11:45:24 -08:00
Xiang (Sean) Zhou e1e0d63616 refactor: Extract reusable function for building agent transfer instructions
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 871410286
2026-02-17 11:19:11 -08:00
Kathy Wu 4285f852d5 fix: Include list of skills in every message and remove list_skills tool from system instruction
The list_skills method is not for model tool listing, but for giving the developer flexibility to load the skill name/description at runtime (from discussion in go/orcas-rfc-555)

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 871406905
2026-02-17 11:12:11 -08:00
Haiyuan Cao ea034877ec fix: Improve BigQuery Agent Analytics plugin reliability and code quality
This CL fixes several bugs in the BigQuery Agent Analytics plugin and refactors the internal data-passing pattern for better type safety and maintainability.

-   **Stale Loop State Validation:** Use `loop.is_closed()` — a public, reliable API — to detect and clean up stale asyncio loop states in `_batch_processor_prop`, `_get_loop_state`, and `flush`. The previous approach used `asyncio.Queue._loop` which is `None` on Python 3.10+, causing the check to always treat states as stale.
-   **Quota Project ID Fallback:** Remove the `or project_id` fallback when setting `quota_project_id` on `BigQueryWriteAsyncClient`. This fixes Workload Identity Federation flows where the federated identity lacks `serviceusage.services.use` on the quota project.
-   **Kwargs Passthrough:** Pass `**kwargs` through to `_log_event` in all callbacks. Previously only model callbacks forwarded them, causing custom attributes (e.g. `customer_id`) to silently drop for agent, tool, run, and error events.
-   **State Delta Logging:** Replace the dead `on_state_change_callback` (never invoked by the framework) with `on_event_callback`, which is already dispatched by the runner for every event. Remove duplicate `STATE_DELTA` logging from `after_tool_callback`.
-   **EventData Dataclass:** Replace the `**kwargs`-as-data-bus pattern in `_log_event` with an explicit `EventData` dataclass. This makes the interface self-documenting, catches typos at construction time, and eliminates shared dict mutation across `_resolve_span_ids`, `_extract_latency`, and `_enrich_attributes`. All 12 callback call sites now construct typed `EventData` instances.
-   **Multi-Subagent Tool Logging Tests:** Add `TestMultiSubagentToolLogging` (6 tests) verifying that tool events are correctly attributed to subagents in multi-turn, multi-agent scenarios. Total tests: 111 (up from 60).

Co-authored-by: Haiyuan Cao <haiyuan@google.com>
PiperOrigin-RevId: 871381533
2026-02-17 10:24:34 -08:00
Google Team Member 6a808c60b3 feat: Introduce User Personas to the ADK evaluation framework
PiperOrigin-RevId: 871366815
2026-02-17 09:54:23 -08:00
Xiang (Sean) Zhou 976a238544 refactor: Extract reusable private methods
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 871359399
2026-02-17 09:36:25 -08:00
Google Team Member 42eeaef2b3 refactor: Extract reusable private methods
PiperOrigin-RevId: 871151624
2026-02-17 00:05:25 -08:00
Xiang (Sean) Zhou 706f9fe74d refactor: Extract reusable private methods
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 871128393
2026-02-16 22:52:47 -08:00
Kathy Wu 4e2d6159ae fix: Fix pickling lock errors in McpSessionManager
When we added the session_lock_map, it resulted in pickling errors during Agent Engine deployment. To fix, we implemented custom getstate and setstate methods to exclude the lock map lock and session lock map from pickling. Closes https://github.com/google/adk-python/issues/4486.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 871056554
2026-02-16 18:50:30 -08:00
Ke Wang fc1f1db005 fix(skill)!: coloate default skill SI with skilltoolset
PiperOrigin-RevId: 870017182
2026-02-13 21:43:54 -08:00
Ke Wang 21be6adcb8 feat: Make skill instruction optimizable and can adapt to user tasks
PiperOrigin-RevId: 869971535
2026-02-13 18:44:46 -08:00
Google Team Member 3fbc27fa4d fix: handle UnicodeDecodeError when loading skills in ADK
PiperOrigin-RevId: 869956988
2026-02-13 17:47:45 -08:00
Xiang (Sean) Zhou d56cb4142c fix: Check both input_stream parameter name and its annotation to decide whether it's a streaming tool that accept input stream
meanwhile also centralize input-stream creation in registration

Move the LiveRequestQueue stream creation from _call_live
(function_tool.py) to the lazy registration block in
_process_function_live_helper (functions.py). This centralizes the
input_stream: LiveRequestQueue annotation check and stream creation
in one place, and ensures the stream is also recreated on
re-invocation after stop_streaming resets it to None.

_call_live now simply passes the existing .stream if set, without
needing to know about LiveRequestQueue at all.

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 869935204
2026-02-13 16:33:26 -08:00
Xiang (Sean) Zhou 1d4b0f9ff5 chore: Replace isinstance call with hasattr call
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 869919864
2026-02-13 15:47:18 -08:00
George Weale 811e50a0cb feat: add generate/create modes for Vertex AI Memory Bank writes
add_events_to_memory now supports memory_write_mode to select generate (event-based extraction/consolidation) or create (direct raw fact writes via memory_facts). This now lets custom memory pipelines while keeping generate as the default path

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 869897256
2026-02-13 14:46:45 -08:00
Anmol Jaiswal d5332f4434 feat: Expand LiteLlm supported models and add registry tests
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 869873309
2026-02-13 13:47:13 -08:00
Liang Wu fbe9eccd05 fix: race condition in table creation for DatabaseSessionService
Using one lock and checking for tables creation instead of schema version.

Closes issue #4445

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 869808097
2026-02-13 11:07:15 -08:00
Xuan Yang 186371f01e chore: Export Context class
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 869796021
2026-02-13 10:38:29 -08:00
Kathy Wu 556d148256 chore: Add readme in skills folder to flag that it is experimental
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 869782185
2026-02-13 10:07:13 -08:00
Akshat8510 30b2ed3ef8 fix(web): allow session resume without new message
Merge https://github.com/google/adk-python/pull/4185

**Description**
 This PR resolves #4100 by making the `new_message` field optional in the `RunAgentRequest` model.

 **The Problem:**
 When attempting to resume an agent session via the FastAPI web server, the request would fail with a `422 Unprocessable Entity` if `new_message` was omitted. This prevented "resume-only" workflows where a user just wants to wake up an existing session.

 **The Solution:**
 Updated `RunAgentRequest.new_message` to be `Optional[types.Content] = None`. The underlying `runner.run_async` logic already supports `None` for resuming purposes, so no further logic changes were required.

 **Verification:**
 Verified that `RunAgentRequest` now validates successfully when `new_message` is missing, defaulting the field to `None`.

Co-authored-by: Liang Wu <wuliang@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4185 from Akshat8510:fix/fastapi-resume-4100 b6d252636aa5f96186507fccf47a278fe733a362
PiperOrigin-RevId: 869761179
2026-02-13 09:11:51 -08:00
Xiang (Sean) Zhou ede925b502 chore: Lazy register all streaming tools
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 869480442
2026-02-12 18:50:43 -08:00
Xiang (Sean) Zhou 5269a6b1d6 chore: Register all streaming tool at runner
previously we only register streaming tool that accept stream input at runner, now uniformly register all streaming tool at runner.

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 869447996
2026-02-12 16:59:36 -08:00
Xiang (Sean) Zhou b53bc555cc fix: Only relay the LiveRequest after tools is invoked
currently we started to relay live request to streaming tool even when the tool was not called yet.

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 869421826
2026-02-12 15:52:45 -08:00
Xuan Yang 647d3b16a3 chore: Unify CallbackContext and ToolContext into the Context class
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 869400758
2026-02-12 15:01:51 -08:00
George Weale 4f71b45425 chore: Add LiteLLM streaming sample
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 869397634
2026-02-12 14:53:56 -08:00
Yifan Wang 9562cd664b chore: expose an endpoint for detailed app info
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 869375052
2026-02-12 14:04:07 -08:00
Google Team Member d85932faa3 chore: Add X-Goog-API-Client header to GDA API requests
PiperOrigin-RevId: 869372484
2026-02-12 13:58:05 -08:00
Liang Wu c6b1c74321 docs: add thinking_config in generate_content_config in example agent
Closes https://github.com/google/adk-python/issues/3905

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 869232930
2026-02-12 08:37:04 -08:00
Liang Wu 4000c0251d chore: remove scipy from eval dependencies
It's not used in the codebase.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 869020801
2026-02-11 21:59:31 -08:00
Liang Wu 845818be44 ci: only use --extra test for unit tests
This can fix unit test github action error by removing `--extra eval`. `--extra a2a` is not needed because it's included in `test`. All tests are still passing.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 869014318
2026-02-11 21:39:48 -08:00
Kathy Wu 9f7d5b3f14 feat: Add load_skill_from_dir() method
This allows users to load skills from a directory and pass it into the SkillToolset constructor.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 868929937
2026-02-11 18:10:54 -08:00
Xuan Yang b7f9110b52 chore: Introduce a unified Context
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 868890552
2026-02-11 16:16:24 -08:00
Yifan 8cd22fb746 chore(version): Bump version and update changelog for 1.25.0
Merge https://github.com/google/adk-python/pull/4455

**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._

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4455 from google:release/candidate f660ec82ff4140ef1deea95182e6e0cc62100f89
PiperOrigin-RevId: 868877872
2026-02-11 15:46:09 -08:00
George Weale 079f7a38be fix: Support escaped curly braces in instruction templates
Close #3527

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 868875061
2026-02-11 15:38:53 -08:00
Google Team Member 34da2d5b26 feat: enable dependency injection for agent loader in FastAPI app gen
This enables to re-use the ADK web interface in other contexts more easily.
For example, when having an own run-time the web interface can be exposed
for visualization during development.

Also add documentation for function.

PiperOrigin-RevId: 868848338
2026-02-11 14:35:35 -08:00
Leon Ziyang Zhang bcbfeba953 feat: pass trace context in MCP tool call's _meta field with Otel propagator
PiperOrigin-RevId: 868841079
2026-02-11 14:18:22 -08:00
Liang Wu 9dccd6a692 feat(conformance): read report's version info from the server
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 868837301
2026-02-11 14:10:57 -08:00
Wei Sun (Jack) 38b4869c41 chore(ci): migrate release pipeline from release-please App to GitHub Actions
Remove the release-please GitHub App config files and add an Actions-based
release pipeline with candidate branch strategy. This includes workflows for
cutting releases, running release-please, finalizing releases, publishing to
PyPI, and cherry-picking fixes to release candidates.

Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 868825704
2026-02-11 13:47:41 -08:00
Hiroaki Sano 657acfadbb docs: Add PostgreSQL session storage sample and documentation
Merge https://github.com/google/adk-python/pull/3926

### Link to Issue or Description of Change

**1. Link to an existing issue (if applicable):**

- Related: #3916

**2. Or, if no issue exists, describe the change:**

**Problem:**
While `DatabaseSessionService` already supports PostgreSQL through SQLAlchemy, there is no documentation or sample code showing users how to configure and use it.

**Solution:**
Add a comprehensive sample under `contributing/samples/postgres_session_service/` that demonstrates:
- How to configure `DatabaseSessionService` with PostgreSQL
- The auto-generated database schema (sessions, events, app_states, user_states tables)
- Connection URL format and configuration options
- A working sample agent with session persistence

### Testing Plan

**Unit Tests:**

- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.

This is a documentation-only change (new sample), so no new unit tests are required. Existing tests continue to pass.

**Manual End-to-End (E2E) Tests:**

Tested locally with the following steps:

1. Started PostgreSQL using `docker compose up -d`
2. Set environment variables:

```bash
export POSTGRES_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/adk_sessions
export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
export GOOGLE_CLOUD_LOCATION=us-central1
export GOOGLE_GENAI_USE_VERTEXAI=true
```
3. Ran `pip install google-adk asyncpg greenlet` to install the required packages
4. Ran `python main.py` - session created successfully
5. Ran `python main.py` again - previous session resumed with event history
6. Verified tables and rows created in PostgreSQL (sessions, events, app_states, user_states)

### Checklist

- [x] I have read the 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 PR adds documentation and a working sample for an already-supported feature. The DatabaseSessionService class already handles PostgreSQL through its DynamicJSON type decorator which uses JSONB for PostgreSQL.

Files added:
- contributing/samples/postgres_session_service/README.md - Comprehensive guide
- contributing/samples/postgres_session_service/agent.py - Sample agent
- contributing/samples/postgres_session_service/main.py - Usage example
- contributing/samples/postgres_session_service/compose.yml - Local PostgreSQL setup
- contributing/samples/postgres_session_service/\_\_init\_\_.py - Package init

Co-authored-by: Liang Wu <wuliang@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3926 from hiroakis:feat-support-pg-for-conversation a5279d4fb2a63699f384c670928d77d882c25a25
PiperOrigin-RevId: 868816317
2026-02-11 13:25:52 -08:00
Liang Wu 61c329f8ce ci: match the environment with internal ones for pyink/isort/unittest
Previously submitted change is causing [Pyink error](https://github.com/google/adk-python/actions/runs/21884351396/job/63176122118) in repo because Pyink recently updated to 25.12.0.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 868806575
2026-02-11 13:01:32 -08:00
Anmol Jaiswal 758d337c76 fix(sessions): use async iteration for VertexAiSessionService.list_sessions pagination
Merge https://github.com/google/adk-python/pull/4435

### Link to Issue or Description of Change

- Closes: #4302

**Problem:**

`VertexAiSessionService.list_sessions()` only returns the first ~100 sessions. The `sessions_iterator` from `api_client.agent_engines.sessions.list()` is an `AsyncPager` — it implements `__aiter__`/`__anext__` for fetching subsequent pages, but the code uses a plain `for` loop which only calls `__iter__`/`__next__`, so it never fetches beyond the first page.

**Solution:**

Changed `for api_session in sessions_iterator` to `async for api_session in sessions_iterator` so the `AsyncPager` actually paginates. Updated the test mock to return an `AsyncIterableList` (supports both sync and async iteration) instead of a bare list, so the tests properly simulate real `AsyncPager` behaviour.

### Testing Plan

**Unit Tests:**

```
$ pytest tests/unittests/sessions/
115 passed, 1 warning in 2.25s
```

The existing `test_list_sessions`, `test_list_sessions_with_pagination`, and `test_list_sessions_all_users` all continue to pass with the updated mock.

Co-authored-by: Liang Wu <wuliang@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4435 from anmolg1997:fix/vertex-ai-session-service-pagination 14c71b607ecbf2215f4b9ba6eb4b0ff6b9eaf740
PiperOrigin-RevId: 868466166
2026-02-10 21:18:51 -08:00
Google Team Member 3cf43e3842 feat: Enhance google credentials config to support externally passed access token
PiperOrigin-RevId: 868390961
2026-02-10 17:21:38 -08:00
Kathy Wu 4aa475145f fix: Fix event loop closed bug in McpSessionManager
Sessions were being erroneously cached and reused across different asyncio event loops, causing "Event loop is closed" in environments with transient loops. This updates the session caching to be loop-aware: before reusing a cached session, check that the stored loop matches the current loop. Also, if session is disconnected and loops do not match, discard the cached entry without calling aclose().

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 868380746
2026-02-10 16:50:53 -08:00
Xiang (Sean) Zhou 7110336788 refactor: Replace check of instance for LlmAgent with hasAttribute check
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 868370272
2026-02-10 16:27:20 -08:00
Google Team Member 0abf4cd2c7 feat: Add a demo simple prompt optimizer for the optimization interface
PiperOrigin-RevId: 868367793
2026-02-10 16:21:11 -08:00
Edwin Kim 40c15d0595 feat(cli): Add --auto_create_session flag to adk api_server CLI
Merge https://github.com/google/adk-python/pull/4288

**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: #4274

**2. Or, if no issue exists, describe the change:**

N/A - Issue exists

### 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.

$ pytest tests/unittests/cli/ -v

============================= test session starts ==============================
platform darwin -- Python 3.11.14, pytest-9.0.2, pluggy-1.6.0
collected 246 items
...
====================== 246 passed, 147 warnings in 21.38s ======================

**Manual End-to-End (E2E) Tests:**

1. Verify CLI flag is recognized:
$ adk api_server --help | grep auto_create_session --auto_create_session
Automatically create a session if it doesn't exist when calling /run.

2. Start server with flag enabled:
$ adk api_server --auto_create_session

3. Test /run endpoint without pre-creating session:
$ curl -X POST http://localhost:8000/run \
  -H "Content-Type: application/json" \
  -d '{"app_name": "my_agent", "user_id": "user1", "session_id": "new_session", "new_message": {"role": "user", "parts": [{"text": "Hello"}]}}'

Expected: Session auto-created, request succeeds (no 404 error).

### 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 PR exposes the existing Runner.auto_create_session functionality (added in commit 8e69a58 / ADK v1.23.0) through the adk api_server CLI command.

Files changed (3 files, ~15 lines):

src/google/adk/cli/cli_tools_click.py - Add --auto_create_session CLI option
src/google/adk/cli/fast_api.py - Pass parameter through get_fast_api_app()
src/google/adk/cli/adk_web_server.py - Store and use in _create_runner()

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4288 from ekimcodes:main 3c8d299a88b21789431dbda488befba7ee3ace81
PiperOrigin-RevId: 868361303
2026-02-10 16:06:01 -08:00
Xuan Yang 2010569010 fix: Preserve thought_signature in function call conversions for interactions API integration
Related: https://github.com/google/adk-python/issues/4311

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 868340444
2026-02-10 15:14:18 -08:00
Google Team Member 7af1858f46 feat: Update agent simulator by improving prompts and add environment data
PiperOrigin-RevId: 868324749
2026-02-10 14:37:03 -08:00
Sasha Sobran e6da417292 fix: propagate grounding and citation metadata in streaming responses
Co-authored-by: Sasha Sobran <asobran@google.com>
PiperOrigin-RevId: 868324488
2026-02-10 14:36:21 -08:00
Didier Durand 6ee5126d1c docs: fixing a typo
Merge https://github.com/google/adk-python/pull/3975

### Link to Issue or Description of Change

Fixing various typos: see commit diffs for details

**1. Link to an existing issue (if applicable):**

- Closes: N/A
- Related: N/A

**2. Or, if no issue exists, describe the change:**

Fixing various typos: see commit diffs for details

**Problem:**

Improve quality of repo

**Solution:**
Pull this P/R

### Testing Plan

N/A
**Unit Tests:**

- [N/A] I have added or updated unit tests for my change.
- [X] All unit tests pass locally.

**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.
- [X] 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/3975 from didier-durand:fix-typos-b ca1cba4e7afe99bb60efffb4de79a2bfe8522ea8
PiperOrigin-RevId: 868308215
2026-02-10 14:01:58 -08:00
George Weale a88e864755 fix: Add post-invocation token-threshold compaction with event retention
Adds optional token_limit and event_retention_size fields to EventsCompactionConfig. When the latest prompt token count meets/exceeds the threshold, ADK compacts older raw events after the invocation and keeps the last N events un-compacted. Updates prompt history building to apply compaction ranges correctly so retained events remain visible.

Close #4146

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 868297968
2026-02-10 13:38:28 -08:00
Liang Wu 25ec2c6b61 feat(web): Add /health and /version endpoints to ADK web server
These endpoints provide basic health checks and version information for the running ADK server, including the ADK version and Python runtime details. The version information will be used to generate ADK conformance test report.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 868283421
2026-02-10 13:07:21 -08:00
Salman Chishti 2f0fe97729 ci: Upgrade GitHub Actions for Node 24 compatibility
Merge https://github.com/google/adk-python/pull/4426

## 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` | [`v4`](https://github.com/actions/checkout/releases/tag/v4) | [`v6`](https://github.com/actions/checkout/releases/tag/v6) | [Release](https://github.com/actions/checkout/releases/tag/v6) | mypy-new-errors.yml, mypy.yml |
| `actions/setup-python` | [`v5`](https://github.com/actions/setup-python/releases/tag/v5) | [`v6`](https://github.com/actions/setup-python/releases/tag/v6) | [Release](https://github.com/actions/setup-python/releases/tag/v6) | mypy-new-errors.yml, mypy.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.

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4426 from salmanmkc:upgrade-github-actions-node24 a574f92c72502ae60531163da60f7820e01380f3
PiperOrigin-RevId: 868281419
2026-02-10 13:02:24 -08:00
Salman Chishti f5702d70bf ci: Upgrade GitHub Actions to latest versions
Merge https://github.com/google/adk-python/pull/4427

## 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 |
|--------|---------------|-------------|---------|-------|
| `astral-sh/setup-uv` | [`v1`](https://github.com/astral-sh/setup-uv/releases/tag/v1), [`v5`](https://github.com/astral-sh/setup-uv/releases/tag/v5), [`v6`](https://github.com/astral-sh/setup-uv/releases/tag/v6) | [`v7`](https://github.com/astral-sh/setup-uv/releases/tag/v7) | [Release](https://github.com/astral-sh/setup-uv/releases/tag/v7) | mypy-new-errors.yml, mypy.yml, python-unit-tests.yml |
| `webfactory/ssh-agent` | [`v0.9.0`](https://github.com/webfactory/ssh-agent/releases/tag/v0.9.0) | [`v0.9.1`](https://github.com/webfactory/ssh-agent/releases/tag/v0.9.1) | [Release](https://github.com/webfactory/ssh-agent/releases/tag/v0) | analyze-releases-for-adk-docs-updates.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.

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4427 from salmanmkc:upgrade-github-actions-node24-general 4aacbae5378233559880ff155e4f478e484c694b
PiperOrigin-RevId: 868263909
2026-02-10 12:20:03 -08:00
George Weale 59e88972ae feat: add add_events_to_memory facade for event-delta
Adds BaseMemoryService.add_events_to_memory(session, events=..., custom_metadata=...) and CallbackContext.add_events_to_memory(events=..., custom_metadata=...) so callers can add memories from an explicit subset of ADK events.

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 868261578
2026-02-10 12:14:52 -08:00
Google Team Member de79bf12b5 feat: log exception details before re-raising in MCP session execution
Adds a logger.exception call to capture traceback and error details when an exception occurs during the execution of a coroutine within an MCP session, before re-raising it as a ConnectionError.

PiperOrigin-RevId: 868253547
2026-02-10 11:56:38 -08:00
Didier Durand 80ff067c6b docs: fixing typo in multiple files
Merge https://github.com/google/adk-python/pull/3944

### 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:** fixing various typos in multiple files: see commit diffs for details

**Problem:**

Discovered typos while reading ADK repo

**Solution:**

Submitted this PR to fix them

### Testing Plan

N/A: changes only in comments, .md and docstrings.

**Unit Tests:**

- [N/A ] I have added or updated unit tests for my change.
- [X] All unit tests pass locally.

_Please include a summary of passed `pytest` results._

**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.
- [X] 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/3944 from didier-durand:fix-typos-a 02378a488d9a87ac9b6b7397fe9ad7c393faf16a
PiperOrigin-RevId: 868245940
2026-02-10 11:38:22 -08:00
sarojrout e0b9712a49 fix: Add endpoints to get/list artifact version metadata
This change introduces new FastAPI endpoints in adk_web_server.py and corresponding client methods in adk_web_server_client.py to allow fetching metadata for artifact versions without downloading the artifact content

Close #3710

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 868217569
2026-02-10 10:40:54 -08:00
George Weale 7c7d25a4a6 fix: Support escaped curly braces in instruction templates
Close #3527

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 868199186
2026-02-10 10:04:39 -08:00
Kathy Wu ec660ed4f0 chore: Add experimental tag to SkillToolset
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 867816959
2026-02-09 16:07:35 -08:00
Filipe Caixeta 19b607684f fix: Strip timezone for PostgreSQL timestamps in DatabaseSessionService
Merge https://github.com/google/adk-python/pull/4365

## Summary
- Fixes `DataError` when using PostgreSQL with `asyncpg` for session storage
- PostgreSQL's default `TIMESTAMP` type is `WITHOUT TIME ZONE`, which cannot accept timezone-aware datetime objects
- The existing code handled this for SQLite but not PostgreSQL - this fix applies the same timezone stripping

## Error
When creating a session with PostgreSQL + asyncpg, the following error occurs:

```
sqlalchemy.dialects.postgresql.asyncpg.Error: <class 'asyncpg.exceptions.DataError'>:
invalid input for query argument $5: datetime.datetime(2026, 2, 3, 21, 32, 50, 353909,
tzinfo=datetime.timezone.utc) (can't subtract offset-naive and offset-aware datetimes)
```

During the INSERT:
```sql
INSERT INTO sessions (app_name, user_id, id, state, create_time, update_time)
VALUES ($1, $2, $3, $4, $5, $6)
```

Where `$5` and `$6` are timezone-aware datetimes being inserted into `TIMESTAMP WITHOUT TIME ZONE` columns.

## Root Cause
Commit 1063fa53 changed from database-generated timestamps (`func.now()`) to explicit Python datetimes (`datetime.now(timezone.utc)`). The SQLite case was handled by stripping the timezone, but PostgreSQL was overlooked.

## Test plan
- [x] Verified fix resolves the error when creating sessions with PostgreSQL + asyncpg
- [ ] Existing unit tests pass

Fixes regression from #1733

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4365 from filipecaixeta:fix-postgresql-timestamp-timezone 9d788ba99e7167a53962d93e59a80f78af091ca9
PiperOrigin-RevId: 867800330
2026-02-09 15:27:42 -08:00
Kathy Wu 8d0279251c feat: Add SkillToolset to adk
Currently supports load skill and load skill resource, scripts support coming later.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 867756231
2026-02-09 13:46:49 -08:00
George Weale f50847460f fix: Per-session locking and row-level locking in DatabaseSessionService.append_event
This change introduces an in-process `asyncio.Lock` per session to serialize `append_event` calls for the same session ID within a single process. For supported database dialects (MySQL, PostgreSQL, MariaDB), it also uses `SELECT ... FOR UPDATE` to acquire row-level locks on the session, app state, and user state records, preventing race conditions across different processes or database connections. A new test case verifies that concurrent updates to stale session objects correctly merge all state changes.

Close #1049

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 867752676
2026-02-09 13:38:38 -08:00
Benson Wang 32ee07df01 fix: prompt token may be None in streaming mode
Merge https://github.com/google/adk-python/pull/3462

**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:**

**Problem:**
When using adk in streaming mode, `usage_metadata.prompt_token_count` may be `None` which will emit log
```Invalid type NoneType for attribute 'gen_ai.usage.input_tokens' value. Expected one of ['bool', 'str', 'bytes', 'int', 'float'] or a sequence of those types```

**Solution:**
Skip setting span attribute if prompt token count is None

**Unit Tests:**

- [x] All unit tests pass locally.

_Please include a summary of passed `pytest` results._

### 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/3462 from wsa-2002:prompt-token-count-may-be-none-in-streaming-mode 94666862f70ed2577d5c55485e67f6da36a57bc6
PiperOrigin-RevId: 867693355
2026-02-09 11:24:22 -08:00
Liang Wu 43c437e38b feat(conformance): add report generation to adk conformance test command
Added `generate_report` and `report_dir` CLI args to the command.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 867689055
2026-02-09 11:15:11 -08:00
George Weale d2dba27134 fix: Pass invocation_id from /run endpoint to Runner.run_async
Close #3290

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 867684592
2026-02-09 11:15:00 -08:00
George Weale 663cb75b32 fix: Conditionally preserve function call IDs in LLM requests
Function call and response IDs generated by ADK are now preserved in the LLM request contents when the agent is using a Gemini model with `use_interactions_api` enabled

Close #4381

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 867675945
2026-02-09 10:46:55 -08:00
George Weale 64a44c2897 fix: Migrate VertexAiMemoryBankService to use the async Vertex AI client
This change updates the VertexAiMemoryBankService to utilize the asynchronous interface provided by `vertexai.Client().aio`. This involves:
-   Retrieving the async client via `_get_api_client().aio`.
-   Awaiting calls to `generate` and `retrieve`.
-   Using `async for` to iterate over the results of the `retrieve` method, as it now returns an async iterator

Close #4386

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 867675311
2026-02-09 10:45:15 -08:00
George Weale 0758f877b1 chore: remove bare excepts
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 867666149
2026-02-09 10:25:03 -08:00
George Weale fd8a9e3962 fix: Handle list values in Gemini schema sanitization
The schema sanitization utility now recursively processes list items, ensuring that properties with list values (e.g., "required") are correctly handled and not altered.

Close #4363

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 867663267
2026-02-09 10:20:08 -08:00
Dinesh Thumma 6bc70a6bab fix(mcp): used logger to log instead of print
Merge https://github.com/google/adk-python/pull/4324

**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: #4320

**2. Or, if no issue exists, describe the change:**

**Problem:**
 Was using print instead of logger for warning message

**Solution:*
Refactored

### Testing Plan

**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._

**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.
- [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

_Add any other context or screenshots about the feature request here._

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4324 from DineshThumma9:logger_in_mcp_session_clean 5eaa9bdc8c3c6697e75b0e876f043d496dd8ee95
PiperOrigin-RevId: 867601662
2026-02-09 07:48:36 -08:00
Wei Sun (Jack) a2e43aaf19 chore(version): Limits sphinx under 9 for docs
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 866569793
2026-02-06 12:34:07 -08:00
Kathy Wu e25227da5e feat: Add a load MCP resource tool
If the user specifies use_mcp_resources=True in their MCPToolset, the agent will be able to load resources with the load_mcp_resource_tool.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 866539602
2026-02-06 11:18:32 -08:00
Kathy Wu c7362100eb feat: Add models.py and prompt.py to adk/skills to use in skill toolset
Also redefined schemas in models.py to be pydantic.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 866270203
2026-02-05 22:06:58 -08:00
Google Team Member 483c5bab94 ADK changes
PiperOrigin-RevId: 866173091
2026-02-05 16:55:06 -08:00
Google Team Member 0b9cbd2d42 feat: Add experimental agent tool simulator
PiperOrigin-RevId: 866160711
2026-02-05 16:21:48 -08:00
Matthew Chan 781f605a1e feat: add base_url option to Gemini LLM class
PiperOrigin-RevId: 866146209
2026-02-05 15:44:00 -08:00
Kacper Jawoszek d9e8e9cf32 fix: otel_to_cloud flag help text points at Cloud Run instead of Agent Engine
Co-authored-by: Kacper Jawoszek <jawoszek@google.com>
PiperOrigin-RevId: 866122815
2026-02-05 14:49:02 -08:00
Wei Sun (Jack) 93a085ad87 chore(version): Bumps version to 1.24.1 patch
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 866107525
2026-02-05 14:13:02 -08:00
Google Team Member 6645aa07fd feat: Add experimental agent tool simulator
PiperOrigin-RevId: 866100611
2026-02-05 13:57:57 -08:00
Yifan Wang 3686a3a98f chore: update adk web files, updated eval dialog colors, and fixed a2ui component types
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 866057812
2026-02-05 12:16:54 -08:00
Yifan Wang ae993e884f fix: adding back deprecated eval endpoint for web until we migrate
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 866049699
2026-02-05 11:58:04 -08:00
George Weale bb89466623 chore: Improve type hints and handle None values in ADK utils
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 866025998
2026-02-05 11:04:46 -08:00
Xuan Yang adbc37fea1 feat: Add progress_callback support to MCPTool and MCPToolset
Fixes: https://github.com/google/adk-python/issues/3811

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 866025995
2026-02-05 11:04:36 -08:00
George Weale 9b112e2d13 fix: Refactor context filtering to better handle multi-turn invocations
The definition of an "invocation" for context filtering has been updated. An invocation now starts with a user message and can include multiple model turns (like the tool calls and responses) until the next user message. The filtering logic has been rewritten to identify invocation start points based on human user messages

Close #4296

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 866023290
2026-02-05 10:57:56 -08:00
Google Team Member a08bf62b95 feat(otel): add extra attributes to span generated with opentelemetry-instrumentation-google-genai
PiperOrigin-RevId: 865825792
2026-02-05 01:58:30 -08:00
Liang Wu e752bbb756 chore: Remove unused tzlocal dependency and logging
The `tzlocal` library and the logging of the local timezone were not used in the `DatabaseSessionService` logic.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 865677320
2026-02-04 18:49:55 -08:00
Wei Sun (Jack) fb941f9011 chore(version): Bump version and update changelog for 1.24.0
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 865651579
2026-02-04 17:26:50 -08:00
Yifan Wang de44bbc17c chore: update adk web
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 865625039
2026-02-04 16:13:51 -08:00
Kathy Wu 7deffb16fd fix: pass tool context into require_confirmation function in McpTool
Aligns with the FunctionTool implementation of require_confirmation. This fixes https://github.com/google/adk-python/issues/4327.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 865566362
2026-02-04 13:55:39 -08:00
nikkie ac1401bd44 fix: Escape Click’s Wrapping in bulled lists of adk web options
Merge https://github.com/google/adk-python/pull/4338

### Link to Issue or Description of Change

**2. Or, if no issue exists, describe the change:**

**Problem:**
Click collapses intended bullet lists in the service URI options.

<img width="709" height="267" alt="image" src="https://github.com/user-attachments/assets/5f74d8a6-f343-41a4-ba6d-570ed0076932" />

**Solution:**
Add `\b` on a line by itself before the formatted block to preserve blank lines.

### Testing Plan

This is format improvement of help message, so I think there is no need to add test case.

**Unit Tests:**

- [ ] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.

```
% pytest tests/unittests/cli  # Python 3.13.8
===================================== 260 passed, 140 warnings in 9.30s ======================================
```

**Manual End-to-End (E2E) Tests:**

`adk web --help`

```
  --session_service_uri TEXT      Optional. The URI of the session service. If set, ADK uses this service.

                                  If unset, ADK chooses a default session service (see
                                  --use_local_storage).
                                  - Use 'agentengine://<agent_engine>' to connect to Agent Engine
                                    sessions. <agent_engine> can either be the full qualified resource
                                    name 'projects/abc/locations/us-central1/reasoningEngines/123' or
                                    the resource id '123'.
                                  - Use 'memory://' to run with the in-memory session service.
                                  - Use 'sqlite://<path_to_sqlite_file>' to connect to a SQLite DB.
                                  - See https://docs.sqlalchemy.org/en/20/core/engines.html#backend-specific-urls
                                    for supported database URIs.
```

### 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/4338 from ftnext:escape-wrapping-web-options-bullet-list 9466731aff293d241cc7ae5728bc3c34c5c89dd6
PiperOrigin-RevId: 865533252
2026-02-04 12:40:13 -08:00
Gabriel Bengo 3c63c2ad39 fix(docs): fix grammar and remove duplicate words in documentation and source
Merge https://github.com/google/adk-python/pull/4335

Fixed 'the the' typos and grammatical errors in README, docstrings, and sample agents.

**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: N/A
- Related: N/A

**2. Or, if no issue exists, describe the change:**

**Problem:**
While exploring the repository, I noticed a few minor writing errors that impact professional readability:
1.  **Grammar:** A subject-verb agreement error in `README.md` and `llms.txt` ("guide the agents works together").
2.  **Duplicate Words:** Several instances of stuttering typos (repeating "the the" or "but the the") in docstrings within `src/` and the `contributing/samples/` directories.

**Solution:**
I have applied the following fixes to improve documentation quality:
*   Corrected phrasing to "guide the agents to work together" in the README.
*   Removed redundant instances of "the" in `eval_metrics.py`, `spanner/settings.py`, and the sample agent docstrings.
*   **No functional code or logic was altered.**

### Testing Plan

**Unit Tests:**

- [x] All unit tests pass locally.

_Summary:_
Since this PR is strictly limited to documentation, comments, and docstrings, no new tests were required. I ran the standard test suite to ensure no syntax errors were accidentally introduced, and everything passed successfully.

**Manual End-to-End (E2E) Tests:**
N/A — This is a static documentation 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. (N/A)
- [ ] I have added tests that prove my fix is effective or that my feature works. (N/A - Doc fix only)
- [x] New and existing unit tests pass locally with my changes.
- [ ] I have manually tested my changes end-to-end. (N/A)
- [x] Any dependent changes have been merged and published in downstream modules.

### Additional context

_None._

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4335 from 88448844:fix-typos-and-docs 200668dad0c216b81d7008d9d6625ac135c9006e
PiperOrigin-RevId: 865530036
2026-02-04 12:31:54 -08:00
George Weale f90adff8c5 fix: Add query parameters to /run_live for advanced run configurations
The /run_live websocket endpoint now accepts proactive_audio, enable_affective_dialog, and enable_session_resumption as query parameters. These parameters control the corresponding settings within the RunConfig used for the live session

Close #4263

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 865441673
2026-02-04 09:24:01 -08:00
Google Team Member 1de65cf314 No public description
PiperOrigin-RevId: 865138065
2026-02-03 18:26:30 -08:00
Xuan Yang 2220d885cd fix: Check will_continue for streaming function calls
Related: https://github.com/google/adk-python/issues/4311

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 865074872
2026-02-03 15:33:44 -08:00
Yifan Wang 37e6507ce4 chore: update adk_web, re-work events, and adding A2UI capabilities
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 865027256
2026-02-03 13:42:44 -08:00
Yeesian Ng 004e15ccb7 feat: Allow passthrough of GOOGLE_CLOUD_LOCATION for AgentEngine deployments
Co-authored-by: Yeesian Ng <ysian@google.com>
PiperOrigin-RevId: 865013321
2026-02-03 13:11:45 -08:00
George Weale 574ec43a17 chore: Improve error handling for LiteLlm import in gemma_llm.py
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 865010258
2026-02-03 13:04:27 -08:00
Liang Wu ce07cd8144 fix(cli): ignore session_db_kwargs for sqlite session services
Close issue #4317

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 864979145
2026-02-03 11:49:13 -08:00
George Weale 706a6dda81 fix: Update OpenTelemetry dependency versions
Relax version constraints for opentelemetry-api and opentelemetry-sdk to allow versions between 1.36.0 and 1.40.0

Close #4229

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 864896212
2026-02-03 08:41:39 -08:00
George Weale da73e718ef fix: Enable pool_pre_ping by default for non-SQLite database engines
This change sets `pool_pre_ping=True` in SQLAlchemy engine kwargs for database backends other than SQLite. This helps ensure that connections from the pool are still valid before being used, preventing issues with stale or disconnected connections. Tests are added to verify the default behavior and that explicit overrides are respected

Close #4211

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 864886767
2026-02-03 08:16:55 -08:00
Google Team Member 125bc85ac5 fix: Resolving MutualTLSChannelError 'OpenSSL' module error on by adding pyopenssl dependency in pyproject.toml
- Add 'pyopenssl' to project dependencies to fix MutualTLSChannelError  encountered during mTLS channel configuration.

PiperOrigin-RevId: 864874340
2026-02-03 07:43:09 -08:00
Google Team Member 6ff10b23be chore: Replace proxy methods with utils implementation
PiperOrigin-RevId: 864802559
2026-02-03 04:01:55 -08:00
Google Team Member f82ceb0ce7 chore: Replace proxy methods with utils implementation
PiperOrigin-RevId: 864773118
2026-02-03 02:27:46 -08:00
George Weale 33012e6dda fix: Make credential key generation stable and prevent cross-user credential leaks
This change updates the credential key generation to use a stable hash (SHA256) instead of Python's built-in hash, which can vary based on PYTHONHASHSEED. It also makes sure that temporary or exchanged OAuth2 fields are excluded from the key calculation. I also added when saving credentials, a copy of the AuthConfig is used to avoid modifying the original shared AuthConfig instance with user-specific exchanged credentials.

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 864599326
2026-02-02 17:51:19 -08:00
George Weale 666cebe369 fix: Add update_timestamp_tz property to StorageSession
This property is a compatibility alias that returns the update timestamp as a POSIX timestamp. It infers whether the database is SQLite using sqlalchemy.inspect to call get_update_timestamp correctly

Close #4334

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 864595914
2026-02-02 17:39:42 -08:00
George Weale dd8cd27b2c chore: Replace print statements with logging in ADK
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 864588921
2026-02-02 17:16:27 -08:00
Max Ind e87a8437fb feat(otel): add extra attributes to span generated with opentelemetry-instrumentation-google-genai
Co-authored-by: Max Ind <maxind@google.com>
PiperOrigin-RevId: 864272319
2026-02-02 03:17:08 -08:00
Google Team Member 7d58e0d2f3 feat: Mark Vertex calls made from non-gemini models
PiperOrigin-RevId: 864253424
2026-02-02 02:23:56 -08:00
Vasilii Novikov 9290b96626 feat: Make OpenAPI tool async
Merge https://github.com/google/adk-python/pull/2872

Closes https://github.com/google/adk-python/issues/787

The OpenAPI tool has been ported to the httpx client to make requests truly asynchronous.

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2872 from condorcet:async_openapi_tool bf83f73af93f624126462fb0bd41fef27c53a0b6
PiperOrigin-RevId: 864250822
2026-02-02 02:15:52 -08:00
Xiang (Sean) Zhou 2770012cec chore: Add sample agent that need to go through oauth flow during mcp tool listing
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 864133951
2026-02-01 20:22:25 -08:00
Xiang (Sean) Zhou 131fbd3948 fix: Fix Pydantic Schema Generation Error for ClientSession
Problem: The test test_openapi_json_schema_accessible was failing because Pydantic couldn't generate a JSON schema for mcp.client.session.ClientSession, which is part of genai_types.ToolListUnion.

Root Cause: The AgentDetails model in src/google/adk/evaluation/app_details.py:37 had tool_declarations: genai_types.ToolListUnion, and ToolListUnion includes mcp.client.session.ClientSession which doesn't have Pydantic core schema support. This model is used in the FastAPI app through EvalCase → Invocation → AppDetails → AgentDetails, causing OpenAPI schema generation to fail.

Solution: Changed the type annotation from genai_types.ToolListUnion to list[Any] in two places:

AgentDetails.tool_declarations
_ToolDeclarations.tool_declarations

This allows Pydantic to generate the OpenAPI schema while maintaining runtime compatibility (the field still accepts the same values).

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 863765002
2026-01-31 16:26:30 -08:00
Xiang (Sean) Zhou 798f65df86 feat(tools): Implement toolset auth for McpToolset, OpenAPIToolset, and others
Update existing toolsets to utilize the new toolset authentication framework. Key changes:
        - McpToolset: Add _auth_config instance variable, _get_auth_headers()
          method to build auth headers from exchanged credentials, and
          get_auth_config() override. Auth headers are now included when
          creating MCP sessions.
        - OpenAPIToolset: Add _auth_config and get_auth_config() to expose
          auth configuration to the framework.
        - ApplicationIntegrationToolset: Add _auth_config and get_auth_config().
        - APIHubToolset: Add _auth_config and get_auth_config().

When ADK resolves toolset auth before calling get_tools(), it populates exchanged_auth_credential on the auth_config. Toolsets can then use this credential when making authenticated requests.

Also update test fixtures in test_apihub_toolset.py to use real auth objects instead of mocks that fail pydantic validation.

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 863764941
2026-01-31 16:25:46 -08:00
Xiang (Sean) Zhou ee873cae2e feat(auth): Add framework support for toolset authentication before get_tools
This change adds framework-level support for resolving toolset authentication before calling get_tools(). Key changes:
    - Add _resolve_toolset_auth() method in BaseLlmFlow that iterates
      through toolsets, checks for auth config, and resolves credentials
      via CredentialManager before tool listing
    - Add TOOLSET_AUTH_CREDENTIAL_ID_PREFIX constant for identifying
      toolset auth requests
    - Add skip logic in auth_preprocessor to not resume function calls
      for toolset auth (they do not need it)
    - Add get_auth_response() method to CallbackContext for retrieving
      auth credentials from session state
    - Update CredentialManager to accept CallbackContext instead of
      requiring ToolContext

When a toolset needs authentication but credentials are not available, the flow yields an adk_request_credential event and interrupts the invocation, allowing the user to complete the OAuth flow before retrying.

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 863543036
2026-01-30 22:36:13 -08:00
Xiang (Sean) Zhou fe82f3cde8 fix!: Make credential manager to accept tool_context instead of callback_context
This seems a breaking change, but actually credential manager is used internally only and also it won't work if some one call it using callback context

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 863534476
2026-01-30 21:59:43 -08:00
George Weale 798d0053c8 fix: Stream errors as simple JSON objects in ADK web server SSE
The ADK web server's /run_sse endpoint now yields a JSON object like {"error": "..."} when an exception occurs during event generation. The adk_web_server_client is updated to detect this error payload and raise a RuntimeError.

Close #4291

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 863475838
2026-01-30 18:18:31 -08:00
George Weale d0102ecea3 fix: Recognize function responses as non-empty parts in LiteLLM
The `_part_has_payload` helper now returns False for parts containing a function response, preventing the addition of fallback user content when a user turn consists solely of tool outputs.

Close #4249

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 863319497
2026-01-30 11:20:50 -08:00
Liang Wu 63a8eba53f fix: Ensure database sessions are always rolled back on errors
Fixes issue#3328

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 863314939
2026-01-30 11:10:02 -08:00
George Weale 47221cd5c1 fix: Handle HTTP/HTTPS URLs for media files in LiteLLM content conversion
For providers that typically require file IDs (like OpenAI and Azure), if a file URI is an HTTP/HTTPS URL and the MIME type is image, video, or audio, convert it to the corresponding URL-based content type (e.g., "image_url") instead of using the generic "file" type

Close #4112

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 863311703
2026-01-30 11:02:29 -08:00
George Weale 2ac468ea7e fix: Add pre-deployment validation for agent module imports
This change introduces a new function, _validate_agent_import, which attempts to import the user's agent.py file before the deployment process begins. This helps catch common issues such as missing dependencies, incorrect relative imports, or syntax errors in the agent code early, providing more informative error messages to the user.

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 863310033
2026-01-30 10:58:15 -08:00
Google Team Member 00aba2d884 feat: Improve asyncio loop handling and test cleanup
This CL enhances asyncio event loop management and test isolation.

-   **BigQuery Analytics Plugin:** Ensure the asyncio event loop is consistently closed within the BigQuery analytics plugin. This prevents potential resource leaks. Add checks to handle potential deadlocks in Python 3.13+ when creating loops during interpreter shutdown.
-   **Test Thread Pool Cleanup:** Introduce a pytest fixture (`cleanup_thread_pools`) to automatically shut down and clear all tool-related thread pools after each test run in `test_functions_thread_pool.py`. This improves test isolation and prevents order-dependent test failures.
-   **Streaming Test Loop Restoration:** Refactor event loop handling in `test_streaming.py`. A new `_run_with_loop` method is introduced in the custom test runners to create a temporary event loop for each test execution, run the coroutine, and crucially, restore the original event loop afterwards. This prevents tests from interfering with each other's loop state.
-   **Resource Closure:** Ensure services are closed properly in tests by adding `await service.close()` in `test_service_factory.py` and using `async with session_service` in `test_session_service.py`.

PiperOrigin-RevId: 863305565
2026-01-30 10:47:09 -08:00
Xuan Yang 585ebfdac7 feat: Support dynamic config for VertexAiSearchTool
Close: https://github.com/google/adk-python/issues/4067

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 862965769
2026-01-29 17:09:49 -08:00
Google Team Member c0c98d94b3 test: Ensure BigQueryAgentAnalyticsPlugin is shut down after each test
Improves test reliability by guaranteeing the BigQueryAgentAnalyticsPlugin is shut down after each test execution. This is achieved by wrapping test logic in try/finally blocks, using a yield fixture, or employing a new asynccontextmanager to ensure the plugin.shutdown() method is always called, preventing potential resource leaks between tests.

PiperOrigin-RevId: 862951816
2026-01-29 16:31:04 -08:00
Xuan Yang 288c2c448d chore: Add ADK logger in RestApiTool
Fixes: https://github.com/google/adk-python/issues/3780

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 862897383
2026-01-29 14:17:52 -08:00
Kathy Wu ecce7e54a6 fix: Change MCP read_resource to return the original contents
Since we will save MCP resource contents to the artifact service, no need to do post-processing based on mime type. Also fixed the implementation; the correct method to call is session.read_resource(uri).

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 862885513
2026-01-29 13:51:45 -08:00
Xiang (Sean) Zhou 381d44cab4 feat: Add get_auth_config method to toolset to expose auth requirement of the toolset
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 862597425
2026-01-29 00:23:24 -08:00
Kathy Wu 4341839420 chore: Convert MCPToolset to McpToolset in unittests
MCPToolset has been deprecated, use McpToolset instead.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 862457868
2026-01-28 17:04:14 -08:00
Sara Robinson 32f9f92042 chore: Add GitHub Action check to run mypy
Merge https://github.com/google/adk-python/pull/4276

This adds 2 mypy GitHub Actions checks:

* `mypy.yml` runs mypy on every PR. This will list all errors, so it shouldn't block until errors are resolved.
* `mypy-new-errors.yml` compares the PR branch to `main` to ensure no new mypy errors are introduced. This check can be made blocking now and can be removed once all errors are resolved in favor of `mypy.yml`.

### 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/4276 from sararob:mypy-gh-actions 63130773c4862e90e352d4cb79221d78a6b9f5fd
PiperOrigin-RevId: 862226296
2026-01-28 07:27:52 -08:00
Google Team Member a16e3cc67e fix: Fix cases where execution_result_delimiters have None type element due to code_execution_result.output is None
PiperOrigin-RevId: 861933883
2026-01-27 16:29:51 -08:00
Kathy Wu 8f7d9659cf feat: Add methods in MCPToolset for users to access MCP resources (read_resource, list_resources, get_resource_info)
This allows users to access MCP resources on their own within agent logic / using custom tools. I plan on also later adding it to the agent state.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 861910520
2026-01-27 15:26:59 -08:00
Google Team Member 3480b3b82d feat: improve error message when failing to get tools from MCP
Include the underlying exception message in the ConnectionError raised when session.list_tools() fails.

PiperOrigin-RevId: 861889733
2026-01-27 14:33:47 -08:00
Liang Wu 65cbf4b35c fix: Make OpenAPI /docs path work again
* The main fix is in eval_metrics.py
* Removed some deprecated paths in the FastAPI server
* Added a unit test to catch future breakages
* Bump fastapi version to be 0.124.1 to capture the fix in https://github.com/fastapi/fastapi/pull/14482
* Removed the upper-bound restriction on fastapi version which was used to temporarily fix the issue

Fixes #3173

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 861867708
2026-01-27 13:41:26 -08:00
Keyur Joshi 4ee125a038 feat: Add interface for agent optimizers
Details:
* The Sampler allows ADK agent optimizers to request evals and receive detailed eval results that can be used to guide agent optimization.
* This interface allows developers to run custom evaluations if needed for their agent. An implementation to interface with the inbuilt LocalEvalService shall be published shortly in a follow-up PR.
* The AgentOptimizer interface describes the general framework for an ADK agent optimizer that uses the Sampler interface to optimize an ADK agent.
* data_types.py contains generic types and base classes to allow intercommunication between the AgentOptimizer, Sampler, and developer code.

Co-authored-by: Keyur Joshi <keyurj@google.com>
PiperOrigin-RevId: 861849691
2026-01-27 12:56:21 -08:00
Xuan Yang 2155a35c51 docs: Update ADK release analyzer to use Gemini 3 Pro with retry and improve file filtering
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 861784867
2026-01-27 10:31:03 -08:00
nikkie 3bcd8f7f7a fix: EscapieClick’s Wrapping in adk eval help (#4258)
Fix https://github.com/google/adk-python/issues/4257

https://click.palletsprojects.com/en/stable/documentation/#escaping-click-s-wrapping

Co-authored-by: Ankur <ankusharma@google.com>
2026-01-27 09:13:55 -08:00
Google Team Member c34615ecf3 fix: disable save_input_blobs_as_artifacts deprecation warning message for users that don't set it
PiperOrigin-RevId: 861738532
2026-01-27 08:38:46 -08:00
Shangjie Chen 1063fa532c fix: Reload the stale session in database_session_service when the update_time of storage is later than the current in memory session object
This changes the behavior of how we handle stale session, instead of reject the transaction entirely, we aggresively refresh the session.

Removed synchronous inspect(self).session calls within StorageSession.update_timestamp_tz and _dialect_name. This introspection was causing deadlocks/hangs when used with sqlalchemy.ext.asyncio in Python 3.13.

Closes issue: https://github.com/google/adk-python/issues/1733

Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 861353058
2026-01-26 14:19:14 -08:00
Ankur Sharma 43d6075ea7 feat: allow Vertex AI Client initialization with API Key
Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 861335865
2026-01-26 13:36:41 -08:00
Joseph Pagadora 553e376718 feat: Remove overall_eval_status calculation from _CustomMetricEvaluator and add threshold to custom metric function expected signature
Co-authored-by: Joseph Pagadora <jcpagadora@google.com>
PiperOrigin-RevId: 861268984
2026-01-26 11:01:32 -08:00
Jinhyuk Kim 85434e293f feat: Pass event id as a metadata when it is converted into a message
PiperOrigin-RevId: 860929058
2026-01-25 16:05:45 -08:00
Google Team Member 324796b4fe feat: This change restructures the bug report template as per intake process
PiperOrigin-RevId: 860304319
2026-01-23 16:43:56 -08:00
Xuan Yang 853a3b0e14 fix: Do not treat FCs and FRs as invisible when marked as thoughts
Related: https://github.com/google/adk-python/issues/4159

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 860254198
2026-01-23 14:25:42 -08:00
Xiang (Sean) Zhou 714c3ad047 feat: Support run tools in separate thread for live mode
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 860242861
2026-01-23 13:55:31 -08:00
George Weale 801233902b fix: fix agent config path handling in generated deployment script
The generated agent deployment script now uses os.path.join and os.path.dirname(__file__) to construct the path to root_agent.yaml. This prevents issues where backslashes in Windows paths could be misinterpreted as Python escape sequences within the f-string, leading to syntax error

Close #4223

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 860236820
2026-01-23 13:39:32 -08:00
Liang Wu 025b42c836 chore: Add unittests.sh script and update CONTRIBUTING.md
This change introduces a new `unittests.sh` script to simplify running unit tests. The script automatically sets up a minimal test environment, runs `pytest`, and then restores the previous development environment. The CONTRIBUTING.md has been updated to include instructions on using this new script.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 860222798
2026-01-23 13:01:06 -08:00
Xiang (Sean) Zhou 753084fd46 refactor: Extract helper function for llm request building and response processing
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 860212868
2026-01-23 12:34:04 -08:00
Google Team Member 2380afd287 feat: Refine Feature Request Issue Template
This change updates the feature request issue template to include required and recommended sections. New questions are added to gather more details on the problem, impact, willingness to contribute, and potential API/implementation ideas. Existing questions are rephrased for clarity

PiperOrigin-RevId: 860199885
2026-01-23 12:00:38 -08:00
Kathy Wu 316463be86 docs: Move mcp session feature out of breaking changes
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 860199237
2026-01-23 11:58:54 -08:00
Xuan Yang 83c24d2e74 docs: Fix ADK release analyzer agent for large releases
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 860187312
2026-01-23 11:29:42 -08:00
Shangjie Chen e8f7aa3140 fix: Add pypika>=0.50.0 to project.toml since crewai depends on it and the default version does not work with py 3.12+
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 860181604
2026-01-23 11:15:19 -08:00
Google Team Member 7edfb2701c docs: update data agent README to match the behavior
PiperOrigin-RevId: 860180180
2026-01-23 11:11:56 -08:00
Max Ind 0d38a3683f fix: remove print debugging artifact
Co-authored-by: Max Ind <maxind@google.com>
PiperOrigin-RevId: 860038888
2026-01-23 03:59:44 -08:00
Kathy Wu 7cf1e447d7 chore: Bumps version to v1.23.0 and updates CHANGELOG.md
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 859790616
2026-01-22 15:03:52 -08:00
Xuan Yang 3f1b0d0957 chore: minor fix for DebugLoggingPlugin example
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 859762221
2026-01-22 14:00:17 -08:00
Max Ind 935c279f82 feat(otel): add minimal generate_content {model.name} spans and logs for non-gemini inference and when opentelemetry-inference-google-genai dependency is missing
Co-authored-by: Max Ind <maxind@google.com>
PiperOrigin-RevId: 859667045
2026-01-22 10:18:06 -08:00
Google Team Member 82fa10b71e feat: add new conversational analytics api tool set
PiperOrigin-RevId: 859449435
2026-01-21 23:31:37 -08:00
Xuan Yang bf2b56de6d fix: recursively extract input/output schema for AgentTool
Fixes: https://github.com/google/adk-python/issues/4154

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 859440231
2026-01-21 23:02:33 -08:00
Liang Wu 3d96b7883b chore: Pin litellm dependency to versions below 1.80.17
This is a stopgap before the actual fix is added for 1.80.17+.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 859351463
2026-01-21 18:43:26 -08:00
Didier Durand 91ec80c606 docs: fixing multiple typos
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
2026-01-21 17:33:51 -08:00
Shangjie Chen 295b345587 chore: Filter out adk_request_input event from content list
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 859321034
2026-01-21 16:55:50 -08:00
lwangverizon b57a3d43e4 feat: Allow google search tool to set different model
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
2026-01-21 14:31:45 -08:00
Google Team Member 9579bea05d feat(plugins): Add flush mechanism to BigQueryAgentAnalyticsPlugin
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
2026-01-21 14:27:03 -08:00
Liang Wu 3e3566bd0e chore: Pin litellm dependency to versions below 1.81.0
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
2026-01-21 13:31:01 -08:00
Xiang (Sean) Zhou a04828dd8a feat: Persist user input content to session in live mode
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 859207592
2026-01-21 12:11:01 -08:00
Didier Durand 5d941460b6 docs: Fix various typos
Merge https://github.com/google/adk-python/pull/4186

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/4186 from didier-durand:main f8a52b58e133551bec1d98660fd552afd881a8b9
PiperOrigin-RevId: 859203551
2026-01-21 12:01:54 -08:00
Xiang (Sean) Zhou e3d542a5ba feat: Support authentication for MCP tool listing
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: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 859201722
2026-01-21 11:57:34 -08:00
Xuan Yang d62f9c896c chore: Always skip executing partial function calls
Related: https://github.com/google/adk-python/issues/4159

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 859184844
2026-01-21 11:20:16 -08:00
Google Team Member 7b25b8fb1d fix(runner): Yield buffered function_call/function_response events during live streaming
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
2026-01-21 10:21:39 -08:00
Kathy Wu 910f65473f docs: Update to gemini-2.5-flash for api registry and mcp sample agents
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 859151854
2026-01-21 10:06:46 -08:00
Google Team Member ab89d12834 refactor(plugins)!: use OpenTelemetry for BigQuery plugin tracing
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
2026-01-21 01:05:53 -08:00
Wei Sun (Jack) 645bd0ed10 docs: Switches to gemini 2.5 flash for two samples
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 858826742
2026-01-20 17:38:53 -08:00
Xiang (Sean) Zhou 1699b090ed chore: Update the comments of request confirmation preprocessor
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 858816547
2026-01-20 17:04:05 -08:00
George Weale 2367901ec5 chore: Upgrade to headers to 2026
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 858763407
2026-01-20 14:50:09 -08:00
Didier Durand a8f2ddd943 chore: fixing various typos
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
2026-01-20 14:21:01 -08:00
George Weale 7955177fb2 fix: Update dependency versions in pyproject.toml
Bump authlib to >=1.6.6 and mcp to >=1.23.0.

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 858728187
2026-01-20 13:29:34 -08:00
George Weale 215c2f506e fix: Set LITELLM_MODE to PRODUCTION before importing LiteLLM
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
2026-01-20 13:16:38 -08:00
Lusha Wang 135f763325 feat: Remove @experimental decorator from AgentEngineSandboxCodeExecutor
Co-authored-by: Lusha Wang <lusha@google.com>
PiperOrigin-RevId: 858706929
2026-01-20 12:36:56 -08:00
George Weale 5257869d91 fix: Redact sensitive information from URIs in logs
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
2026-01-20 12:27:27 -08:00
Xuan Yang 53b67ce634 feat: Add --disable_features CLI option to ADK CLI
This flag can be used to override default feature enable state.

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 858659818
2026-01-20 10:45:32 -08:00
Wiktoria Walczak 21f63f66ee feat(cli): add otel_to_cloud flag to adk deploy agent_engine command
Co-authored-by: Wiktoria Walczak <wwalczak@google.com>
PiperOrigin-RevId: 858546581
2026-01-20 05:41:39 -08:00
Xuan Yang 69ad605bc4 feat: Use json schema for base_retrieval_tool, load_artifacts_tool, and load_memory_tool declaration when feature enabled
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 858435881
2026-01-19 23:36:53 -08:00
Liang Wu 4b29d15b3e fix: Handle async driver URLs in migration tool
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
2026-01-19 19:39:20 -08:00
Xiang (Sean) Zhou 3dd7e3f1b9 chore: Update sample live streaming tools agent to use latest live models
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 858001541
2026-01-18 21:04:06 -08:00
Google Team Member 81eaeb5eba fix: Remove custom metadata from A2A response events
PiperOrigin-RevId: 857331378
2026-01-16 15:47:38 -08:00
ShaharKatz 7d4326c360 Handle None inferences in eval results for issue #2729 (#3805)
* fixed CR comments

* formatted via isort

---------

Co-authored-by: Ankur <ankusharma@google.com>
2026-01-16 12:35:08 -08:00
Ankur Sharma c222a45ef7 chore: Making the regex to catch cli reference strict by adding word boundary anchor
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
2026-01-16 12:10:02 -08:00
Joseph Pagadora ea0934b993 feat: Update adk eval cli to consume custom metrics by adding CustomMetricEvaluator
Co-authored-by: Joseph Pagadora <jcpagadora@google.com>
PiperOrigin-RevId: 857229167
2026-01-16 11:05:52 -08:00
Peter Kaplan 5923da786e feat: Add is_computer_use field to agent information in adk-web server
PiperOrigin-RevId: 857218915
2026-01-16 10:41:47 -08:00
Google Team Member f92d4e397f fix: Make all parts of a thought event be marked as thought
PiperOrigin-RevId: 857218905
2026-01-16 10:40:58 -08:00
Google Team Member 7dc6adf4e5 feat: migrate ToolboxToolset to use toolbox-adk and align validation
### 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
2026-01-16 08:27:16 -08:00
Liang Wu d0aef8a4fa docs: Update the migration guide for adding a new database session schema
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 856882485
2026-01-15 17:13:08 -08:00
Akshat8510 e162bb8832 feat: Allow thinking_config in generate_content_config
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
2026-01-15 14:32:06 -08:00
Kathy Wu 19315fe557 feat: Support authentication for MCP tool listing
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
2026-01-15 13:38:19 -08:00
Yeesian Ng 6dbe851fca chore: Add back unit tests for CLI utility to deploy to AgentEngine
Co-authored-by: Yeesian Ng <ysian@google.com>
PiperOrigin-RevId: 856749290
2026-01-15 11:43:07 -08:00
George Weale 6ad18cc2fc fix: Use json.dumps for error messages in SSE events
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 856737497
2026-01-15 11:14:02 -08:00
Yeesian Ng 83d7bb6ef0 fix: Use the correct path for config-based agents when deploying to AgentEngine
Co-authored-by: Yeesian Ng <ysian@google.com>
PiperOrigin-RevId: 856724694
2026-01-15 10:45:58 -08:00
Xiang (Sean) Zhou 19555e7dce fix: Support Generator and Async Generator tool declaration in JSON schema
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 856713741
2026-01-15 10:19:58 -08:00
Google Team Member ed2c3ebde9 fix: Prevent stopping event processing on events with None content
PiperOrigin-RevId: 856706510
2026-01-15 10:03:40 -08:00
nikkie 50c4b8d33a chore: Disable scheduled GitHub Actions workflows in forks
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
2026-01-15 09:25:19 -08:00
Anantha Narayanan 7db3ce9613 fix: 'NoneType' object is not iterable
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
2026-01-14 23:32:53 -08:00
Xuan Yang 2ed686527a feat: Use json schema for IntegrationConnectorTool declaration when feature enabled
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 856508415
2026-01-14 23:09:44 -08:00
Xiang (Sean) Zhou ec6abf4010 fix: Use canonical tools to find streaming tools and use tool.name to register them
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
2026-01-14 21:00:20 -08:00
Xiang (Sean) Zhou 7c282973ea fix: Support Generator and AsyncGenerator tool declaration
use yield type as return type

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 856459995
2026-01-14 19:56:34 -08:00
Kathy Wu d4da1bb733 fix: Initialize self._auth_config inside BaseAuthenticatedTool
So that we can access self._auth_config in McpTool for getting auth headers

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 856451693
2026-01-14 19:19:08 -08:00
Kathy Wu cce430da79 feat: start and close ClientSession in a single task in McpSessionManager
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
2026-01-14 18:10:03 -08:00
Google Team Member 1133ce219c feat: convert A2UI messages between A2A DataPart metadata and ADK events
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
2026-01-14 17:07:54 -08:00
Xiang (Sean) Zhou 712b5a393d fix: Only filter out audio content when sending history
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
2026-01-14 16:51:19 -08:00
George Weale 89bed43f5e fix: Add finish reason mapping and remove custom file URI handling in LiteLLM
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
2026-01-14 16:44:44 -08:00
Kathy Wu 8264211f98 chore: Consolidate test_mcp_toolset.py into one file
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
2026-01-14 16:37:12 -08:00
Xuan Yang 8e7cc16f12 docs: Refactor ADK release analyzer with workflow agents
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 856412858
2026-01-14 16:19:02 -08:00
George Weale fdc98d5c92 fix: Convert unsupported inline artifact MIME types to text in LoadArtifactsTool
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
2026-01-14 16:01:06 -08:00
Xiang (Sean) Zhou 7b035aa9fc chore: Always log api backend when connecting to live model
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 856404282
2026-01-14 16:00:15 -08:00
Google Team Member 672b57f1b7 chore: add a sample BigQuery agent using BigQuery MCP tools
PiperOrigin-RevId: 856400285
2026-01-14 15:49:23 -08:00
Kotaro Saito 38d52b2476 fix(cli): pass log_level to uvicorn in web and api_server commands (#4144)
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
2026-01-14 09:48:32 -08:00
Xuan Yang 79fcddb39f feat: Add --enable_features CLI option to ADK CLI
This flag can be used to override default feature enable state.

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 856067979
2026-01-13 23:58:26 -08:00
Xuan Yang 8973618b0b chore: Add a DebugLoggingPlugin to record human readable debugging logs
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 856067925
2026-01-13 23:57:36 -08:00
lwangverizon 8e69a58df4 feat: Add support to automatically create a session if one does not exist
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
2026-01-13 21:23:49 -08:00
Xiang (Sean) Zhou 1bedffe457 chore: Remove dead codes for flushing model audio when generation completes
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
2026-01-13 12:28:24 -08:00
Google Team Member 277084e313 refactor(tools): Update ToolboxToolset to wrap toolbox-adk
### 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
2026-01-13 10:59:51 -08:00
Xiang (Sean) Zhou ab62b1bffd fix: Use the agent name as the author of the audio event
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 855789317
2026-01-13 10:38:53 -08:00
Xiang (Sean) Zhou f668a5de44 chore: Update comments about why we can return upon flushing audio caches
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 855788674
2026-01-13 10:37:28 -08:00
Xuan Yang a5f0d333d7 feat: Use json schema for RestApiTool declaration when feature enabled
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 855767527
2026-01-13 09:50:59 -08:00
Google Team Member fd2c0f556b chore: Upgrade the sample BQ agent model version to gemini-2.5-flash
This change should give a more intelligent out-of-the-box experience to the sample BigQuery agent users.

PiperOrigin-RevId: 855552871
2026-01-12 23:30:16 -08:00
Joseph Pagadora 6d2f33a59c feat: Update EvalConfig and EvalMetric data models to support custom metrics
Co-authored-by: Joseph Pagadora <jcpagadora@google.com>
PiperOrigin-RevId: 855517478
2026-01-12 21:37:21 -08:00
George Weale 905604faac refactor: Import migration_runner lazily within the migrate command
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 855496468
2026-01-12 20:21:57 -08:00
Xiang (Sean) Zhou a4732a8e50 chore: Updatedate the doc string of LiveRequest
activity_start, activity_end , and blob is sent via send_realtime_input, according to the docstring : https://github.com/googleapis/python-genai/blob/d98c757c7d9a88026ac0f9eb2b1b578e2e7f3bfe/google/genai/live.py#L251, they should be send separately, so makes sense they are mutally exclusive.

And we already make them exclusive in our current logic:
https://github.com/google/adk-python/blob/6c0bf85042c38c7bafe1c183f1bba8bee1ba3570/src/google/adk/flows/llm_flows/base_llm_flow.py#L264-L272, make it clear in docstring

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 855492864
2026-01-12 20:06:08 -08:00
Liang Wu 75231a30f1 fix: Handle NOT_FOUND error when fetching Vertex AI sessions
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 855464349
2026-01-12 18:17:41 -08:00
Alexis Marasigan b725045e5a fix: fix httpx client closure during event pagination
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
2026-01-12 17:27:29 -08:00
Google Team Member a4116a6cbf feat: Enhance TraceManager async safety, enrich BigQuery plugin logging, and fix serialization
*   **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
2026-01-12 15:46:12 -08:00
Liang Wu 2592f01eb6 chore: Bumps version to v1.22.1 and updates CHANGELOG.md
Fixing two bugs found in v1.22.0.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 855343807
2026-01-12 12:43:36 -08:00
George Weale 6c0bf85042 fix: add back migration_runner in cli_tools_click
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 855327486
2026-01-12 12:03:45 -08:00
Kathy Wu 7c8bc69dd0 fix: Ensure open api tool service account exchanger uses quota project id for ADC
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
2026-01-12 11:51:59 -08:00
George Weale 5880109ab1 fix: Set empty JSON string as placeholder for redacted content in traces
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
2026-01-12 11:15:28 -08:00
Tim Niemueller 458d24e24e fix: Convert examples for A2A agent card
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
2026-01-12 10:37:24 -08:00
Xiang (Sean) Zhou 4a34501d38 chore: Remove unnecessary assert of live request queue
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
2026-01-12 10:30:07 -08:00
George Weale 43b484ff66 fix: Handle file URI conversion for LiteLLM based on provider and model
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
2026-01-12 10:10:50 -08:00
Dinesh Thumma 94d48fce32 fix: Database reserved keyword issue
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
2026-01-09 18:20:46 -08:00
Google Team Member 2bd984adb3 feat: Add option to send full history to stateless RemoteA2aAgents
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
2026-01-09 17:32:20 -08:00
Google Team Member 59eda98eae feat: add SpannerVectorStore for orchestrating and providing utility functions for a Spanner vector store
PiperOrigin-RevId: 854392465
2026-01-09 16:58:44 -08:00
Liang Wu 8fb2be216f chore: Add back adk migrate session CLI
It was accidentally deleted in a previous PR. Closes #4107.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 854339442
2026-01-09 14:13:17 -08:00
Xuan Yang 6b241f5ef2 feat: Use json schema for agent tool declaration when feature enabled
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 854329254
2026-01-09 13:45:46 -08:00
saroj rout 86e7664006 feat(runners): Allow app_name to override app.name when both provided
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
2026-01-09 13:35:11 -08:00
Xuan Yang 0fe3870cd5 chore: Migrate the rest of tools to use the new feature decorator
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 854295648
2026-01-09 12:14:16 -08:00
George Weale fdc286a23c fix: Handle mixed tool and non-tool parts in LiteLLM content conversion
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
2026-01-09 10:15:13 -08:00
Wiktoria Walczak 62fa4e513c feat(cli): add otel_to_cloud flag to adk deploy cloud_run and adk deploy gke command
Co-authored-by: Wiktoria Walczak <wwalczak@google.com>
PiperOrigin-RevId: 854087382
2026-01-09 01:43:22 -08:00
Xiang (Sean) Zhou 4dd5434847 chore: Make live request queue required
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 854058723
2026-01-09 00:05:14 -08:00
Xiang (Sean) Zhou d6c964e05e fix: Create a new session resumption config if it's None
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 853933839
2026-01-08 16:49:52 -08:00
Kathy Wu 23d330eef1 feat: Include model ID with token usage for live events
This allows users to track token usage data per model and fixes https://github.com/google/adk-python/issues/4084.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 853925212
2026-01-08 16:22:56 -08:00
George Weale b8917bc80e fix: Handle SQLite URLs in SqliteSessionService
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
2026-01-08 16:14:07 -08:00
Sasha Sobran 3c51ee7f48 fix: fix SSRF vulnerability in load_web_page by disabling automatic redirects
Co-authored-by: Sasha Sobran <asobran@google.com>
PiperOrigin-RevId: 853901476
2026-01-08 15:13:27 -08:00
Kathy Wu f1ccc0cfca feat: Support page token in API Registry
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
2026-01-08 14:15:02 -08:00
Xiang (Sean) Zhou 8e41f7f6c8 chore: Annotate the type of transcription parameter in _has_non_empty_transcription_text
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 853880336
2026-01-08 14:14:05 -08:00
Joseph Pagadora da2c933b53 feat: Filter invocation and eval case rubrics by type when running rubric based evaluators
Co-authored-by: Joseph Pagadora <jcpagadora@google.com>
PiperOrigin-RevId: 853841204
2026-01-08 12:23:33 -08:00
Kathy Wu 226e873b0f fix: Ensure consistent ADC quota project override in ADK
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
2026-01-08 12:22:45 -08:00
Joseph Pagadora 8afb99a078 feat: Support per-eval case and per-invocation rubrics in rubric-based evaluators
Co-authored-by: Joseph Pagadora <jcpagadora@google.com>
PiperOrigin-RevId: 853820099
2026-01-08 11:26:06 -08:00
Liang Wu 688791396a chore: Bumps version to v1.22.0 and updates CHANGELOG.md
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 853816883
2026-01-08 11:18:10 -08:00
George Weale 6c67b6c0f4 fix: map LiteLLM thought parts to reasoning_content
- 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
2026-01-08 10:10:13 -08:00
Xiang (Sean) Zhou 9b2bd411dd chore: Put user_id in the error message when session is not found
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 853771033
2026-01-08 09:19:31 -08:00
Xiang (Sean) Zhou 392dda1e0c chore: Update live multi agent sample with latest live models
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 853769664
2026-01-08 09:14:45 -08:00
Google Team Member a0b2aac108 fix: Add google-cloud-geminidataanalytics to dependencies
PiperOrigin-RevId: 853515315
2026-01-07 19:57:53 -08:00
Google Team Member 3cd3d56176 fix: Add google-cloud-geminidataanalytics to dependencies
PiperOrigin-RevId: 853504915
2026-01-07 19:19:24 -08:00
Google Team Member c34feb4c0e feat: add new conversational analytics api tool set
PiperOrigin-RevId: 853489874
2026-01-07 18:26:05 -08:00
Google Team Member aaf76a6a51 feat: add new conversational analytics api tool set
PiperOrigin-RevId: 853434500
2026-01-07 15:23:43 -08:00
Yifan Wang 45a25d780b chore: update adk web to match main branch
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 853331843
2026-01-07 10:58:37 -08:00
George Weale 5912835c97 fix: Add checks for event content and parts before accessing
Close #3769

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 853327479
2026-01-07 10:48:14 -08:00
George Weale b30c2f4e13 fix: avoid local .adk storage in Cloud Run/GKE
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
2026-01-07 10:18:11 -08:00
Xiang (Sean) Zhou d5bd8d939e chore: Clean up the invocation context initialization logic for LIVE
1. Removed dead code: The if not run_config.response_modalities: branch was never executed since run_live already sets the default (https://github.com/google/adk-python/blob/19de45b3250d09b9ec16c45788e7d472b3e588c2/src/google/adk/runners.py#L947-L948).
2. Simplified condition: Changed from checking 'TEXT' not in ... to 'AUDIO' in ...

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 853274401
2026-01-07 08:31:01 -08:00
Sasha Sobran 96c5db5a07 fix: use mode='json' in model_dump to serialize bytes correctly when using telemetry
fixes #4043

Co-authored-by: Sasha Sobran <asobran@google.com>
PiperOrigin-RevId: 853256045
2026-01-07 07:38:18 -08:00
Xuan Yang 10bdc078a4 chore: Add docstring for StreamingMode
Related: #3705

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 853116282
2026-01-07 00:15:12 -08:00
Xiang (Sean) Zhou a4b914b09f fix: Set the default response modality to AUDIO only
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
2026-01-06 23:47:08 -08:00
Xiang (Sean) Zhou 19de45b325 fix: Honor the modalities parameter in adk api server for live API
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 853077949
2026-01-06 22:06:57 -08:00
George Weale b28721508a feat: make LlmAgent.model optional with a default fallback
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
2026-01-06 17:56:14 -08:00
George Weale 742c9265a2 fix: Validate app name in adk create command
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
2026-01-06 17:37:36 -08:00
Xiang (Sean) Zhou 9403a44f34 chore: Cleanup the workaround logic for streamlit
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 852995899
2026-01-06 17:18:49 -08:00
Liang Wu 35308d3809 chore: add min version of Google Auth to include fix
Context: https://github.com/googleapis/python-genai/commit/930c7ca7d5b696d3388fe16fb724184eb88c6a65. The GenAI SDK relies on Google Auth for the fix, and adding this as a direct dependency in ADK will decouple the release of ADK and GenAI SDK.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 852990837
2026-01-06 17:01:16 -08:00
Xiang (Sean) Zhou ecc9f182e3 chore: remove unecessary event loop creation in LiveRequstQueue constructor
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
2026-01-06 16:57:23 -08:00
George Weale 6dce7f8a8f fix: Add schema type sanitization to OpenAPI spec parser
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 #3704
Close #3108

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852986491
2026-01-06 16:47:06 -08:00
Liang Wu ce64787c3e feat: Add database schema migration command and script
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
2026-01-06 16:36:45 -08:00
George Weale 0827d12ccd fix: Prevent .env files from overriding existing environment variables
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
2026-01-06 16:31:24 -08:00
Liang Wu 8329fec0fc chore: Add disambiguation message to enterprise_search_tool
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 852969034
2026-01-06 15:56:22 -08:00
George Weale 1ace8fc678 fix: Filter out thought parts in lite_llm._get_content
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
2026-01-06 15:44:33 -08:00
George Weale 084fcfaba5 fix: Split SSE events with both content and artifactDelta in ADK Web Server
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
2026-01-06 14:51:37 -08:00
George Weale 1ae0e16b2c fix: Remove fallback to cached exchanged credential in _load_existing_credential
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
2026-01-06 14:50:05 -08:00
George Weale 30d3411d60 fix: Prevent retry_on_errors from retrying asyncio.CancelledError
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
2026-01-05 14:58:26 -08:00
Xiang (Sean) Zhou 6f2c70fc33 chore: add docstring for BIDI streaming mode
BIDI streaming mode is not used currently.

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 852461564
2026-01-05 14:41:09 -08:00
George Weale fc4e3d6f60 fix: Fix double JSON encoding when saving eval set results
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
2026-01-05 14:26:05 -08:00
Michael Jones bfed19cd78 feat: expose mcps streamable http custom httpx factory parameter
Merge https://github.com/google/adk-python/pull/3634

Reopen of https://github.com/google/adk-python/pull/2997 after the accepted changes in that PR were reverted by https://github.com/google/adk-python/commit/e15e19da05ee1b763228467e83f6f73e0eced4b5

---

This PR addresses https://github.com/google/adk-python/issues/3005 and https://github.com/google/adk-python/issues/2963 to allow control over the ssl cert used when connecting to an mcp server by exposing the `httpx_client_factory` parameter exposed when creating a `MCPSessionManager` in adk. Overlaps with https://github.com/google/adk-python/pull/2966 but I don't believe that that PR's implementation will work. `streamablehttp_client` needs a client factory, not a client.

## testing plan

Adds test checking that `streamablehttp_client` uses the custom httpx factory. Could also test that a factory which obeys the `McpHttpClientFactory` protocol produces valid behavior when the session is opened?

## related issues

#2227 and #2881 both request _slightly different_ options to control the ssl certs used internally by adk. I think exposing a httpx factory is a good pattern which could be followed for those issues too.

Co-authored-by: Kathy Wu <wukathy@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3634 from mikeedjones:feat/expose-mcps-streamable-http-custom-httpx-factory-parameter 1017a9875c697b28b96a7a8d1311494ef89af65a
PiperOrigin-RevId: 852443631
2026-01-05 13:57:26 -08:00
George Weale e3db2d0d83 fix: Propagate RunConfig custom metadata to all events
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
2026-01-05 13:30:09 -08:00
George Weale 4ddb2cb2a8 chore: Close database engines to avoid aiosqlite pytest hangs
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852428755
2026-01-05 13:18:08 -08:00
Google Team Member 8789ad8f16 fix: Include back-ticks around the BQ asset names in the tools examples
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
2026-01-05 12:52:49 -08:00
George Weale 93d6e4c888 fix: Allow string values for ToolTrajectoryCriterion.match_type
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
2026-01-05 12:43:53 -08:00
Xiang (Sean) Zhou e850e9c9ba chore: Update disconnecting log message
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
2026-01-05 12:30:15 -08:00
George Weale 838530ebe0 fix: rehydration of EventActions in StorageEvent.to_event
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
2026-01-05 12:26:10 -08:00
Mimi Sun 8bed01cbdc fix: make the BigQuery analytics plugin work with agents that don't have instructions such as the LoopAgent
PiperOrigin-RevId: 852382657
2026-01-05 11:21:25 -08:00
George Weale e32f017979 fix: Prevent ContextFilterPlugin from creating orphaned function responses
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
2026-01-05 11:09:52 -08:00
George Weale 688f48fffb fix: Update empty event check to include executable code and execution results
Close #3859
Close #3921

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 852375447
2026-01-05 11:04:34 -08:00
George Weale 6f259f08b3 fix: Harden YAML builder tmp save/cleanup
- 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
2026-01-05 10:47:12 -08:00
Rohit Yanamadala 3ec7ae3b8d fix: ignore adk-bot administrative actions in stale agent
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
2026-01-05 10:45:58 -08:00
George Weale 6b7386b762 fix: Heal missing tool results before LiteLLM requests
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
2026-01-05 09:49:20 -08:00
Joseph Pagadora 5b7c8c04d6 chore: Introduce MetricInfoProvider interface, and refactor metric evaluators to use this interface to provide MetricInfo
Co-authored-by: Joseph Pagadora <jcpagadora@google.com>
PiperOrigin-RevId: 851406110
2026-01-02 11:49:34 -08:00
Google Team Member 07bb164758 fix: Exclude thought parts when merging agent output
PiperOrigin-RevId: 850500329
2025-12-30 13:39:40 -08:00
Keyur Joshi a364388d97 feat: Add custom instructions support to LlmBackedUserSimulator
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
2025-12-30 11:42:46 -08:00
Keyur Joshi 0918b647df fix: fix inconsistent method signatures for evaluate_invocations
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
2025-12-30 11:07:25 -08:00
Yeesian Ng 38a30a44d2 fix: Handle overriding of requirements when deploying to agent engine
Co-authored-by: Yeesian Ng <ysian@google.com>
PiperOrigin-RevId: 850423017
2025-12-30 08:30:35 -08:00
Google Team Member 26e77e1694 fix: Fix issue with MCP tools throwing an error
Fixes: https://github.com/google/adk-python/issues/3082
PiperOrigin-RevId: 849562638
2025-12-27 15:51:03 -08:00
Yeesian Ng 1f546df35a feat: Set log level when deploying to Agent Engine
Co-authored-by: Yeesian Ng <ysian@google.com>
PiperOrigin-RevId: 848243087
2025-12-23 11:25:39 -08:00
Google Team Member 871571d997 feat: Mark Vertex calls made from non-gemini models
PiperOrigin-RevId: 848159669
2025-12-23 06:50:46 -08:00
Google Team Member 0f5b677c53 feat: Mark Vertex calls made from non-gemini models
PiperOrigin-RevId: 848140103
2025-12-23 05:37:36 -08:00
Google Team Member 4f3b733074 fix: label response as thought if task is immediately returned as working
PiperOrigin-RevId: 847660113
2025-12-22 01:21:41 -08:00
Xuan Yang 0b1cff2976 feat: Enable PROGRESSIVE_SSE_STREAMING feature by default
Related: https://github.com/google/adk-python/issues/3705

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 846793027
2025-12-19 10:50:49 -08:00
Kathy Wu 71b32890f5 fix: Only prepend "https://" to the MCP server url if it doesn't already have a scheme
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
2025-12-18 16:07:16 -08:00
Rohit Yanamadala f51b9b70b2 fix: Prevent stale bot from flagging internal maintainer discussions
Merge https://github.com/google/adk-python/pull/3938

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3938 from ryanaiagent:fix/stale-bot-logic 605d3499784facffc0e0ca3c1fb0547202660f46
PiperOrigin-RevId: 846450195
2025-12-18 16:04:21 -08:00
Google Team Member e4ee9d7c46 feat: Update event_converter used in A2ARemote agent to use a2a_task.status.message only if parts are non-empty
PiperOrigin-RevId: 846413612
2025-12-18 14:23:27 -08:00
Xiang (Sean) Zhou f1eb1c0254 chore: Update latest Live Model names for sample agent
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 846351549
2025-12-18 11:33:18 -08:00
Xiang (Sean) Zhou d58ea589ad chore: Update google-genai and google-cloud-aiplatform versions
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 846307170
2025-12-18 09:42:15 -08:00
Xuan Yang f5f4c01d1b fix: Pin aiosqlite version to 0.21.0
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 846056994
2025-12-17 21:26:19 -08:00
Kathy Wu 253ac87c79 fix: nit fixes for API Registry - updating imports / type hints and formatting
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 845980315
2025-12-17 17:23:58 -08:00
Kathy Wu 0088b0f3ad fix: Add x-goog-user-project header to http calls in API Registry
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
2025-12-17 16:41:50 -08:00
George Weale fcea86f58c chore: Update _flatten_ollama_content return type and add tests
The return type of _flatten_ollama_content is now strictly str | None

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 845963722
2025-12-17 16:31:43 -08:00
Google Team Member f35d129b4c feat(fix): Check all content parts for emptiness in _contains_empty_content
PiperOrigin-RevId: 845954226
2025-12-17 16:03:12 -08:00
Shangjie Chen 589f15cb27 feat: Add an internal function name 'adk_framework' to allow passing function response to the framework but not poluting the agent context
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 845933584
2025-12-17 15:07:25 -08:00
Kathy Wu 78c96e99ff fix: update Api Registry Agent prompt to be more specific and give it the gcloud project id
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 845884290
2025-12-17 13:00:19 -08:00
George Weale e3bac1ab8c fix: Built-in agents (names starting with "__") now use in-memory session storage instead of creating .adk folders in the agents directory
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 845852695
2025-12-17 11:36:22 -08:00
George Weale c6f389d4bc fix: Refine Ollama content flattening and provider checks
- 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
2025-12-17 11:25:44 -08:00
Salman Chishti 1add41e160 fix: Upgrade GitHub Actions for Node 24 compatibility
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
2025-12-17 10:01:43 -08:00
Salman Chishti fa717ad8f0 fix: Upgrade GitHub Actions to latest versions
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
2025-12-17 09:37:58 -08:00
Google Team Member 43270bcb61 fix: Move and enhance the deprecation warning for the plugins argument in "_validate_runner_params" to the beginning of the function
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
2025-12-17 06:48:44 -08:00
Goodnight 322dd1827a docs: Fix typos, broken links, and grammar across documentation
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
2025-12-16 22:45:02 -08:00
Hiroaki Sano 42317f849f fix: Add missing space in README.md
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
2025-12-16 22:33:06 -08:00
Liang Wu ba91fea541 feat: Use new JSON-based schema for newly-created databases
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
2025-12-16 14:49:31 -08:00
Xiang (Sean) Zhou 2ea6e513cf feat: support regex for allowed origins
fixes https://github.com/google/adk-python/issues/3908

Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 845397350
2025-12-16 12:53:35 -08:00
Kamal Aboul-Hosn b6f6dcbeb4 feat: Add a handwritten tool for Cloud Pub/Sub
Merge https://github.com/google/adk-python/pull/3865

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3865 from kamalaboulhosn:main 37a38a4dcadb04a0af0ec584e6f611204a63cd2a
PiperOrigin-RevId: 845345128
2025-12-16 10:48:09 -08:00
Liang Wu 7e6ef71eec feat: Introduce new database schema for DatabaseSessionService
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
2025-12-15 17:32:48 -08:00
Xuan Yang a0885064b0 chore: Add override_feature_enabled to override the default feature enable states
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 844905911
2025-12-15 13:46:17 -08:00
Liang Wu e8ab7dafa9 chore: Move SQLite migration script to migration/ folder
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 844902789
2025-12-15 13:38:51 -08:00
Hiroaki Sano 8335f35015 fix: Change error_message column type to TEXT in DatabaseSessionService
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
2025-12-15 11:09:25 -08:00
Google Team Member e515e0f321 feat: Introduce a post-hoc, per-turn evaluator for user simulations
PiperOrigin-RevId: 844818512
2025-12-15 10:05:31 -08:00
Marlin Ranasinghe 69997cd5ef fix: oauth refresh not triggered on token expiry
Merge https://github.com/google/adk-python/pull/3767

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3767 from MarlzRana:marlzrana/fix-oauth-refresh-not-triggered-on-token-expiry 2dae3917de6e8d3fa5317857d06305d47c0773b0
PiperOrigin-RevId: 843756363
2025-12-12 10:57:58 -08:00
George Weale 5c4bae7ff2 fix: Add MIME type inference and default for file URIs in LiteLLM
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
2025-12-12 10:51:55 -08:00
David Sullivan 8782a69503 feat: add token_endpoint_auth_method support to OAuth2 credentials
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
2025-12-12 10:16:36 -08:00
Xiang (Sean) Zhou 29c1115959 chore: Bumps version to v1.21.0 and updates CHANGELOG.md
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 843427582
2025-12-11 16:54:08 -08:00
Liang Wu 60e314a78f fix: Update SQLite database URL for async connection
The example is broken without the fix.

Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 843424168
2025-12-11 16:42:10 -08:00
George Weale ee9b4ca908 feat: Add .yml to watched file extensions and add unit tests for AgentChangeEventHandler
Close #3834

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 843409166
2025-12-11 16:00:17 -08:00
George Weale db711cd789 fix: Redirect LiteLLM logs from stderr to stdout
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
2025-12-11 15:14:15 -08:00
George Weale 055dfc7974 fix: Normalize multipart content for LiteLLM's ollama_chat provider
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
2025-12-11 14:46:37 -08:00
Yifan Wang df8684734b chore: update adk web, fixes image not rendering, state not updating, update drop down box width and trace icons
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 843378628
2025-12-11 14:36:40 -08:00
Google Team Member 9cccab4537 fix: installing dependencies for py 3.10
PiperOrigin-RevId: 843378433
2025-12-11 14:35:51 -08:00
Xuan Yang e1a7593ae8 feat: Add header_provider to OpenAPIToolset and RestApiTool
Fixes: https://github.com/google/adk-python/issues/3782

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 843352147
2025-12-11 13:29:00 -08:00
Xuan Yang cb3244bb58 feat: Use json schema for function tool declaration when feature enabled
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 843350330
2025-12-11 13:24:41 -08:00
George Weale 894d8c6c26 fix: Refactor LiteLLM response schema formatting for different models
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 #3713
Close #3890

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 843326850
2025-12-11 12:20:11 -08:00
George Weale 99f893ae28 fix: Resolve project and credentials before creating Spanner client
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
2025-12-11 12:03:10 -08:00
Google Team Member 7b2fe14dab feat: Upgrade BigQueryAgentAnalyticsPlugin to v2.0
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
2025-12-10 23:04:01 -08:00
Xiang (Sean) Zhou 68d70488b9 chore: Add sample agent for interaction api integration
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 843037705
2025-12-10 21:37:03 -08:00
Xiang (Sean) Zhou c6320caaa5 feat: Support interactions API for calling models
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 843032402
2025-12-10 21:21:14 -08:00
Xiang (Sean) Zhou f0bdcaba44 chore: Update genAI SDK version
Co-authored-by: Xiang (Sean) Zhou <seanzhougoogle@google.com>
PiperOrigin-RevId: 843030125
2025-12-10 21:13:52 -08:00
George Weale 7b356ddc1b feat: Add add_session_to_memory to CallbackContext and ToolContext
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
2025-12-10 20:47:08 -08:00
Krishna vamsi Dhulipalla 4111f85b61 docs(adk): fix run_async example and correct ticketId payload key
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
2025-12-10 17:24:58 -08:00
Xuan Yang b23deeb9ab docs: Update adk docs update workflow to invoke the updater agent once per suggestion
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 842789476
2025-12-10 10:45:05 -08:00
Xuan Yang 51a638b6b8 chore: Introduce build_function_declaration_with_json_schema to use pydantic to generate json schema for FunctionTool
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 842783745
2025-12-10 10:31:09 -08:00
George Weale 6388ba3b20 fix: Avoid false positive "App name mismatch" warnings in Runner
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
2025-12-10 10:08:37 -08:00
Google Team Member 4f54660d6d fix: Update the code to work with either 1 event or more than 1 events
Update the code to work with either 1 event or more than 1 events.

PiperOrigin-RevId: 842406345
2025-12-09 14:48:25 -08:00
Xiang (Sean) Zhou ee743bd19a chore: Update component definition for triaging agent
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
2025-12-09 14:25:18 -08:00
Xuan Yang bab57296d5 chore: Migrate Google tools to use the new feature decorator
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 842321126
2025-12-09 11:21:06 -08:00
Xuan Yang 1ae944b39d chore: Migrate computer to use the new feature decorator
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 842287104
2025-12-09 10:03:43 -08:00
hoonji 32e87f6381 feat: Adds ADK EventActions to A2A response
Merge https://github.com/google/adk-python/pull/3631

### Link to Issue or Description of Change

**1. Link to an existing issue (if applicable):**

- Closes: #3630

**Solution:**
Adds [Event.actions](https://github.com/google/adk-python/blob/a3aa07722a7de3e08807e86fd10f28938f0b267d/src/google/adk/events/event.py#L51) to A2A event metadata during ADK -> A2A event conversion (to allow A2A event consumers to access important info like state_delta, artifact delta, etc)

### Testing Plan

`pytest ./tests/unittests` passes

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3631 from hoonji:main 31d3a49ad630bbd778aa4cf62dd9ccfc50f5b7af
PiperOrigin-RevId: 842274939
2025-12-09 09:32:36 -08:00
George Weale 56775afc48 fix: OpenAPI schema generation by skipping JSON schema for judge_model_config
Close #3750

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 841991676
2025-12-08 18:20:41 -08:00
Google Team Member cde7f7c243 feat: Allow overriding connection template
PiperOrigin-RevId: 841984336
2025-12-08 17:54:25 -08:00
Xuan Yang 82e6623fa9 fix: Add tool_name_prefix support to OpenAPIToolset
Fixes: https://github.com/google/adk-python/issues/3779

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 841850614
2025-12-08 11:35:08 -08:00
Google Team Member 143ad44f8c fix: pass context to client inceptors
PiperOrigin-RevId: 840918430
2025-12-05 16:26:20 -08:00
Google Team Member f22bac0b20 feat: add Spanner execute sql query result mode
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
2025-12-05 16:00:42 -08:00
George Weale de841a4a09 chore: Improve error message for missing invocation_id and new_message in run_async
Help with issue in #3801

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 840833736
2025-12-05 12:34:18 -08:00
Google Team Member b7ce5e17b6 fix: Yield event with error code when agent run raised A2AClientHTTPError
PiperOrigin-RevId: 840816236
2025-12-05 11:45:47 -08:00
Xuan Yang 9d2388a46f feat: Add SSL certificate verification configuration to OpenAPI tools
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
2025-12-05 11:30:03 -08:00
Kacper Jawoszek 711df01e73 feat(otel): remove experimental status from otel_to_cloud
Co-authored-by: Kacper Jawoszek <jawoszek@google.com>
PiperOrigin-RevId: 840703872
2025-12-05 06:39:07 -08:00
Google Team Member a9b853fe36 fix: ApigeeLLM support for Built-in tools like GoogleSearch, BuiltInCodeExecutor when calling Gemini models through Apigee
PiperOrigin-RevId: 840459113
2025-12-04 16:57:30 -08:00
George Weale 3d444cc953 chore: Ignore the .adk/ directory
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 840387909
2025-12-04 13:54:17 -08:00
Google Team Member 82bd4f380b fix: Extract and propagate task_id in RemoteA2aAgent
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
2025-12-04 13:25:46 -08:00
George Weale c557b0a1f2 fix: Update FastAPI and Starlette to fix CVE-2025-62727 (ReDoS vulnerability)
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
2025-12-04 13:18:59 -08:00
davidkl97 f2735177f1 fix(oauth): add client id to token exchange
Merge https://github.com/google/adk-python/pull/2805

fixes #2806
add client id to token request, adhering to [RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3)

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2805 from davidkl97:fix/oauth-exchange-token 3366dce65ce4dd4fee649a81ab7e486689637442
PiperOrigin-RevId: 840369113
2025-12-04 13:09:42 -08:00
George Weale 2b64715505 fix: Handle string function responses in LiteLLM conversion
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
2025-12-03 19:17:16 -08:00
George Weale 0a07a667e9 feat: Change service creation and add app name mapping for sessions
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
2025-12-03 18:27:16 -08:00
Doug Reid e9182e5eb4 feat: Add Gemma3Ollama model integration and a sample
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
2025-12-03 18:27:07 -08:00
Lin-Nikaido b0c3cc6e36 fix: Support file uploads for OpenAI/Azure in LiteLLM
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
2025-12-03 18:26:27 -08:00
George Weale bb8a269079 fix: Extract and propagate task_id in RemoteA2aAgent
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
2025-12-03 18:25:41 -08:00
Łukasz Lipiński 507424acb9 feat: Add location for table in agent events in plugin BigQueryAgentAnalytics
Merge https://github.com/google/adk-python/pull/3784

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3784 from lipinski:fix/add-location-to-bigqueryagentanalytics 8d88b2c3ad849b22e14a8d74185bfe348fd2503b
PiperOrigin-RevId: 839980070
2025-12-03 17:25:03 -08:00
Xuan Yang 92821b8dda docs: Remove the duplicated label instructions for the ADK triaging agent
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 839970998
2025-12-03 16:55:35 -08:00
Ankur Sharma 960b206752 chore: Bumps version to v1.20.0 and updates CHANGELOG.md
Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 839930279
2025-12-03 15:03:25 -08:00
Bo Yang 5947c41b55 chore: Update component owners
Co-authored-by: Bo Yang <ybo@google.com>
PiperOrigin-RevId: 839896507
2025-12-03 13:40:48 -08:00
Shangjie Chen 9d918d45df feat!: Rollback the DB migration as it is breaking
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 839818479
2025-12-03 10:39:43 -08:00
George Weale 8c9105bf14 chore: Drop Python 3.9 support, set minimum to Python 3.10
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 839799108
2025-12-03 09:56:22 -08:00
George Weale e02b9fb608 fix: Add a warning when deploying with the ADK Web UI enabled
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
2025-12-03 09:47:13 -08:00
Rohit Yanamadala 76dc169a83 fix: Add editLimit parameter to GraphQL query
Merge https://github.com/google/adk-python/pull/3771

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3771 from google:ryanaiagent-patch-1 a169e728af223594febc39299e046f2a195d606a
PiperOrigin-RevId: 839620767
2025-12-03 00:16:14 -08:00
Kathy Wu b638a48357 fix: Update API Registry Toolset to prod cloudapiregistry URL now that it is available
Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 839547174
2025-12-02 20:17:38 -08:00
Faraaz Ahmed b807d62fe3 feat(bigquery): Add labels support to BigQueryToolConfig for job tracking and monitoring
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
2025-12-02 19:15:20 -08:00
Xuan Yang 3aef9a18b1 docs: Update ADK issue triaging agent to add component label before planned
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 839391092
2025-12-02 12:54:44 -08:00
Shangjie Chen 77401132d1 chore: Add migration guide for DatabaseSessionService
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 839376632
2025-12-02 12:15:52 -08:00
Google Team Member 090711934f feat: add Spanner vector_store_similarity_search tool
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
2025-12-02 11:18:57 -08:00
Hangfei Lin 8da61be45a fix: Flush pending transcriptions on turn/generation complete or interrupt for Gemini API
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
2025-12-01 18:09:29 -08:00
George Weale 98d82935e6 fix: allow LlmAgent model to be provided via CodeConfig
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
2025-12-01 16:31:22 -08:00
George Weale 7e8eeca6aa fix: Add a FastAPI endpoint for saving artifacts
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
2025-12-01 16:29:18 -08:00
George Weale ed9da3fa45 feat!: Introduction of ADK folder for local session and artifact storage
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
2025-12-01 16:22:35 -08:00
Keyur Joshi dd827af2ee chore: Move simulation related modules to a sub-package in evaluation
Co-authored-by: Keyur Joshi <keyurj@google.com>
PiperOrigin-RevId: 838904075
2025-12-01 13:16:12 -08:00
Rohit Yanamadala cb19d0714c fix: Optimize Stale Agent with GraphQL and Search API to resolve 429 Quota errors
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
2025-12-01 12:25:51 -08:00
Ankur Sharma 2a1a41d3ec chore: Adding Eval Client label to model calls made during evals
Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 838857867
2025-12-01 11:20:46 -08:00
Eitan Yarmush 8e82838f1e fix: Refactor Anthropic integration to support both direct API and Vertex AI
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
2025-12-01 11:04:51 -08:00
Ishan Raj Singh 7edd7ea9b7 chore: Add warning for full resource path in VertexAiMemoryBankService agent_engine_id
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
2025-12-01 10:51:47 -08:00
Shangjie Chen 0094eea3ca feat!: Migrate DatabaseSessionService to use JSON serialization schema
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
2025-11-26 19:49:08 -08:00
Xuan Yang 786aaed335 feat: Support streaming function call arguments in progressive SSE streaming feature
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 837172244
2025-11-26 10:15:31 -08:00
George Weale 73e5687b9a fix: Remove 'per_agent' from kwargs when using remote session service URIs
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 837169299
2025-11-26 10:08:13 -08:00
Kathy Wu ec4ccd718f feat: Create APIRegistryToolset to add tools from Cloud API registry to agent
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
2025-11-26 10:01:58 -08:00
George Weale f283027e92 feat: expose service URI flags
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
2025-11-25 11:13:03 -08:00
George Weale 06e6fc9132 feat: wire runtime entrypoints to service factory defaults
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
2025-11-25 10:47:44 -08:00
happyryan 5453b5bfde fix: Allow image parts in user messages for Anthropic Claude
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
2025-11-25 10:30:08 -08:00
Hangfei Lin 5cad8a7f58 fix: Throw warning when using transparent session resumption in ADK Live for Gemini API key
transparent session resumption is only supported in Vertex AI APIs

Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 836715170
2025-11-25 10:04:57 -08:00
Virtuoso633 d29261a3dc feat(models): Enable multi-provider support for Claude and LiteLLM
Merges: https://github.com/google/adk-python/pull/2810

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 836706608
2025-11-25 09:46:44 -08:00
Bastien Jacot-Guillarmod e6be5bc9c6 fix: Add type annotations to Runner.__aenter__
PiperOrigin-RevId: 836614561
2025-11-25 04:45:00 -08:00
Om Kute c6e7d6b16a feat(tools): Add debug logging to VertexAiSearchTool
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
2025-11-24 17:29:50 -08:00
Xuan Yang b331d97dfb docs: Remove the list_unlabeled_issues tool from the issue triaging agent
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 836416597
2025-11-24 17:14:51 -08:00
qieqieplus 4a42d0d9d8 feat: Add enum constraint to agent_name for transfer_to_agent
Merge https://github.com/google/adk-python/pull/2437

Current implementation of `transfer_to_agent` doesn't enforce strict constraints on agent names, we could use JSON Schema's enum definition to implement stricter constraints.

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2437 from qieqieplus:main 052e8e73b9d61c0998573a2077f15864873d0dd7
PiperOrigin-RevId: 836410397
2025-11-24 16:51:36 -08:00
Shangjie Chen 728abe4d81 feat(agents): Add warning for duplicate sub-agent names
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 836409638
2025-11-24 16:48:45 -08:00
Google Team Member 4eb2a11403 fix: fix bug where remote a2a agent wasn't using its a2a part converter
PiperOrigin-RevId: 836399603
2025-11-24 16:18:18 -08:00
Kristen Pereira a1c09b724b fix: Windows Path Handling and Normalize Cross-Platform Path Resolution in AgentLoader
Merge https://github.com/google/adk-python/pull/3609

Co-authored-by: George Weale <gweale@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3609 from p-kris10:fix/windows-cmd 8cb0310bd4450097a0a7714eaac6521b6a447442
PiperOrigin-RevId: 836395714
2025-11-24 16:07:40 -08:00
AlexeyChernenkoPlato cf21ca3584 fix: double function response processing issue
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
2025-11-22 09:34:05 -08:00
Shangjie Chen a9a418ba87 fix: Remove distructive validation
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 835466120
2025-11-21 20:56:39 -08:00
George Weale 2e1f730c3b fix: Update LiteLLM system instruction role from "developer" to "system"
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
2025-11-21 15:56:04 -08:00
Xuan Yang 52674e7fac fix: Update AgentTool to use Agent's description when input_schema is provided in FunctionDeclaration
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 835379243
2025-11-21 15:25:27 -08:00
davidkl97 777dba3033 feat(tools): Add an option to disallow propagating runner plugins to AgentTool runner
Merge https://github.com/google/adk-python/pull/2779

Fixes #2780

### testing plan
not available as is doesn't introduce new functionality

Co-authored-by: Wei Sun (Jack) <weisun@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2779 from davidkl97:feature/agent-tool-plugins a602c808789f3daeed6244e352a6fb8fb6972de3
PiperOrigin-RevId: 835366974
2025-11-21 14:49:36 -08:00
saroj rout 2247a45922 feat(agents): add validation for unique sub-agent names (#3557)
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
2025-11-21 14:24:07 -08:00
Adrian Altermatt 609c6172d9 docs: too many E(inv=2, role=user) plus reformatting
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
2025-11-21 13:49:01 -08:00
Giorgio Boa 9d331abb4e ci: bump action scripts versions
Merge https://github.com/google/adk-python/pull/3638

Thanks for this great project 👏
This PR updates the GitHub actions dependencies to the latest version.

### 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.

Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3638 from gioboa:ci/actions-versions f7d6f3b5233e8cb135c8af88d5b6e0ead8382055
PiperOrigin-RevId: 835343177
2025-11-21 13:39:46 -08:00
Rohit Yanamadala 23f1d8914a docs(agent): Implement stale issue bot
Merge https://github.com/google/adk-python/pull/3546

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3546 from ryanaiagent:feat/stale-issue-agent bcf45098c1c6406b4a42228e4a8ef02f12840425
PiperOrigin-RevId: 835327931
2025-11-21 12:54:20 -08:00
Shangjie Chen 5583bb819b chore: Update MCP requirement to >1.10.0
Resolves https://github.com/google/adk-python/issues/3644

Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 835302097
2025-11-21 11:43:32 -08:00
Shangjie Chen 89aee16f16 chore: Allow google-cloud-storage >=2.18.0
Resolves https://github.com/google/adk-python/issues/3641

Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 835292931
2025-11-21 11:18:40 -08:00
Max Ind a4453c884c fix: adk deploy agent_engine uses correct URI during an update
Co-authored-by: Max Ind <maxind@google.com>
PiperOrigin-RevId: 835269976
2025-11-21 10:17:57 -08:00
Google Team Member 11df1e886d fix: Change pass to yield in BaseLlmConnection.receive
PiperOrigin-RevId: 835268090
2025-11-21 10:12:19 -08:00
Austin Wise 59eba96ea4 fix: Remove unused, incorrect import
PiperOrigin-RevId: 835247166
2025-11-21 09:10:04 -08:00
Google Team Member 631b58336d fix: Content is marked non empty if its first part contains text or inline_data or file_data or func call/response
PiperOrigin-RevId: 835063599
2025-11-20 22:19:28 -08:00
George Weale a3e4ad3cd1 fix: Update session last update time when appending events
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
2025-11-20 18:27:02 -08:00
George Weale 848fdbef7c fix: Filter out None values from enum lists in schema generation
Close #3552

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 834967220
2025-11-20 17:02:45 -08:00
George Weale 31cfa3b82b feat: Capture thinking output, forward raw payloads, and fix exec locals
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
2025-11-20 16:30:19 -08:00
Dylan b57fe5f459 feat(web): add list-apps-detailed endpoint
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
2025-11-20 14:15:06 -08:00
Issac cd54f48fed fix: fix paths for public docs
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
2025-11-20 12:26:43 -08:00
George Weale 084c2de0da fix: Make sure request bodies without explicit names are named 'body'
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
2025-11-20 11:48:46 -08:00
George Weale bf8b85da52 fix: save sessions with camelCase aliases
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
2025-11-20 11:41:41 -08:00
Holt Skinner caf23ac49f docs: Add Code Wiki badge to README
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
2025-11-20 10:00:29 -08:00
Kathy Wu a3aa07722a fix: Update the retry_on_closed_resource decorator to retry on all errors
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
2025-11-19 17:50:49 -08:00
Shangjie Chen a6e4d6c0d9 chore: Bumps version to v1.19.0 and updates CHANGELOG.md
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 834503873
2025-11-19 17:12:56 -08:00
Divyansh Shukla 8fc6128b62 fix: Fix out of bounds error in _run_async_impl
PiperOrigin-RevId: 834492696
2025-11-19 16:36:35 -08:00
Xuan Yang 679d543f8e docs: Update ADK triaging agent to only triage planned issues
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
2025-11-19 16:26:55 -08:00
Google Team Member f13a11e1dc feat: Propagate application_name set for the BigQuery Tools as BigQuery job labels
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
2025-11-19 16:02:32 -08:00
George Weale 131d39c3db fix: Change name for builder agent
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
2025-11-19 16:00:51 -08:00
George Weale 12db84f5cd fix: Remove app name from FileArtifactService directory structure
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 834462462
2025-11-19 15:12:48 -08:00
Ankur Sharma dc3f60cc93 chore: Plumb memory service from LocalEvalService to EvaluationGenerator
Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 834398581
2025-11-19 12:28:52 -08:00
Yifan Wang 14e3802643 chore: update adk web to match main branch
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 834378696
2025-11-19 11:37:29 -08:00
Shangjie Chen ffbab4cf4e chore: Add BigQuery related label handling
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 834375503
2025-11-19 11:29:40 -08:00
George Weale b2b7f2d6aa chore: Move adk_agent_builder_assistant to built_in_agents
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 834371390
2025-11-19 11:18:37 -08:00
Hangfei Lin 3ad30a58f9 fix: Add transcription fields to session events
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
2025-11-19 11:08:38 -08:00
George Weale 0ac35b23dc docs: Add path sanitization for model-generated file paths
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 834344352
2025-11-19 10:13:16 -08:00
Mimi Sun 857de04deb feat: update save_files_as_artifacts_plugin to never keep inline data
PiperOrigin-RevId: 834328794
2025-11-19 09:36:42 -08:00
Max Ind e15e19da05 fix: remove hardcoded google-cloud-aiplatform version in agent engine requirements
This fixes e.g. `--trace_to_cloud flag`

Co-authored-by: Max Ind <maxind@google.com>
PiperOrigin-RevId: 834190152
2025-11-19 02:01:34 -08:00
Michael Jones 0cc3d6d6d5 Feat/expose mcps streamable http custom httpx factory parameter (#2997)
* feat: Add support for custom HTTPX client factory in StreamableHTTPConnectionParams

* Update src/google/adk/tools/mcp_tool/mcp_session_manager.py

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* unit tested mock

* provide default - httpx client factory can't be none

* feat: Enhance StreamableHTTPConnectionParams with httpx_client_factory attribute

* fmt

* fmt

* refactor: Rename test_init_with_streamable_http_none_httpx_factory to test_init_with_streamable_http_default_httpx_factory for clarity

* isort

* fmt

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Kathy Wu <108756731+wukath@users.noreply.github.com>
2025-11-18 11:09:48 -08:00
Hangfei Lin b5f5df9fa8 fix(runners): Ensure event compaction completes by awaiting task
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
2025-11-18 10:57:50 -08:00
George Weale a12ae812d3 feat: Add service factory for configurable session and artifact backends
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
2025-11-18 10:35:31 -08:00
Shangjie Chen 8eb1bdbc58 chore: Add demo for rewind
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 833871446
2025-11-18 10:26:15 -08:00
George Weale 236f562cd2 fix: Load agent/app before creating session
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
2025-11-18 09:09:22 -08:00
Google Team Member 4dd28a3970 feat: Add id and custom_metadata fields to MemoryEntry
PiperOrigin-RevId: 833581243
2025-11-17 18:34:03 -08:00
Ankur Sharma b2c45f8d91 chore: Enhance the messaging with possible fixes for RESOURCE_EXHAUSTED errors from Gemini
Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 833538475
2025-11-17 16:15:56 -08:00
Google Team Member 5ac5129fb0 feat: Enhance BQ Plugin Schema, Error Handling, and Logging
This update enhances the BigQuery agent analytics plugin:

*   **Enhanced Error Logging:** Improved error messages for schema mismatches.
*   **Reordered Logging Content:** Prioritized metadata in `before_model_callback`.

PiperOrigin-RevId: 833508755
2025-11-17 15:00:38 -08:00
Google Team Member c642f13f21 feat: Thread custom_metadata through forwarding artifact service
PiperOrigin-RevId: 833496193
2025-11-17 14:25:30 -08:00
Kathy Wu a48a1a9e88 fix: Improve logic for checking if a MCP session is disconnected
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
2025-11-17 14:05:02 -08:00
Xuan Yang a5ac1d5e14 feat: Add progressive SSE streaming feature
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 833483804
2025-11-17 13:55:38 -08:00
George Weale 0ec01956e8 fix: keep vertex session event history intact
Close #3504

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 833417574
2025-11-17 11:13:08 -08:00
George Weale 840283228e feat!: Raise minimum Python version to 3_10
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 833363352
2025-11-17 09:02:58 -08:00
Xuan Yang 1dd97f5b45 fix: Add experimental feature to use parameters_json_schema and response_json_schema for McpTool
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 833144947
2025-11-16 20:55:16 -08:00
Wei Sun (Jack) f7f6837fde docs: Add python tips to AGENTS.md to assist vibe coding
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 832772144
2025-11-15 14:08:04 -08:00
George Weale 2dea5733b7 fix: add type hints in cleanup_unused_files.py
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
2025-11-14 17:58:37 -08:00
Xuan Yang 871da731f1 feat: Add feature decorator for the feature registry system
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 832503990
2025-11-14 16:48:09 -08:00
Shangjie Chen 9211f4ce8c fix: Use async for to loop through event iterator to get all events in vertex_ai_session_service
Fix https://github.com/google/adk-python/issues/3559

Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 832476367
2025-11-14 15:22:27 -08:00
Kathy Wu a754c96d3c fix: Improve logic for checking if a MCP session is disconnected
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
2025-11-14 14:33:39 -08:00
anrzeszutek 29fea7ec1f fix: Fix deploy to cloud run on Windows
Merge https://github.com/google/adk-python/pull/3536

- Closes: #1597
- Related: #3306

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3536 from anrzeszutek:main ab9f6bfcd51b373934c0c03ef41c880ce224b31d
PiperOrigin-RevId: 832441843
2025-11-14 13:41:58 -08:00
Google Team Member 7c993b01d1 feat: Schema Enhancements with Descriptions, Partitioning, and Truncation Indicator
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
2025-11-14 13:28:45 -08:00
Ankur Sharma 696852a280 chore: Add default retry options as fall back to llm_request that are made during evals
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
2025-11-14 11:02:54 -08:00
milkisbad 9b754564b3 fix: status code in error message in RestApiTool
Merge https://github.com/google/adk-python/pull/2819

add status code to http error to make it more verbose

issue: https://github.com/google/adk-python/issues/2820

# testing plan
run new tests that have beed added in PR

Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2819 from milkisbad:rest_api_tool_verbose_error 79ac6d96174d414e7ca958379102cfa7ede0e883
PiperOrigin-RevId: 832367374
2025-11-14 10:24:21 -08:00
George Weale 0fa7e4619d fix: Add jsonschema dependency for Agent Builder config validation
Close #3494

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 832362832
2025-11-14 10:10:30 -08:00
Google Team Member b7d571bc3f chore: make readability improvements in ADK BQ tool tests
PiperOrigin-RevId: 832110063
2025-11-13 19:43:25 -08:00
Google Team Member 5adbf95a0a fix: stop updating write mode in the global settings during tool execution
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
2025-11-13 18:02:19 -08:00
Xuan Yang 23ad40bad2 feat: Introduce a feature registry system for ADK
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 832050198
2025-11-13 16:14:49 -08:00
Yeesian Ng b8e4aedfbf fix: Add vertexai initialization for code being deployed to AgentEngine
Co-authored-by: Yeesian Ng <ysian@google.com>
PiperOrigin-RevId: 832031219
2025-11-13 15:23:24 -08:00
Google Team Member ffbb0b37e1 feat: allow setting max_billed_bytes in BigQuery tools config
This will allow users to configure a limit to access in ADK tools on the charges for queries.

PiperOrigin-RevId: 831921163
2025-11-13 10:42:56 -08:00
George Weale 22eb7e5b06 feat: Add support for parsing inline JSON tool calls in LiteLLM responses
Close #1968

Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 831911719
2025-11-13 10:18:27 -08:00
Sara Robinson 2efc184a46 chore: Add support for abstract types in AFC
PiperOrigin-RevId: 831873580
2025-11-13 08:38:25 -08:00
Google Team Member 6bb0b7417e chore: Add abstract type annotation support to AFC
PiperOrigin-RevId: 831545133
2025-11-12 14:39:43 -08:00
Liang Wu 69627b699f chore: Implement lazy loading for modules within google.adk.tools
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
2025-11-12 14:17:26 -08:00
Hangfei Lin 0ab79b9502 fix: Deprecate save_live_audio in favor of save_live_blob and fix audio event saving
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
2025-11-12 13:16:13 -08:00
George Weale 675ecaa8db feat!: Upgrade to include python3.14
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
2025-11-12 13:09:00 -08:00
Google Team Member d12468ee5a feat: add a2a_request_meta_provider to RemoteAgent init
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
2025-11-12 13:04:06 -08:00
Hangfei Lin 5d5708b2ab chore: Add debug logging for live connection
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
2025-11-12 11:36:08 -08:00
Sara Robinson 52b1dfea14 chore: Add abstract type annotation support to AFC
PiperOrigin-RevId: 831462920
2025-11-12 11:11:41 -08:00
Liang Wu 22c6dbe83c chore: Defer import of live, Client and _transformers in google.genai
Co-authored-by: Liang Wu <wuliang@google.com>
PiperOrigin-RevId: 831444358
2025-11-12 10:27:56 -08:00
George Weale a19be12c1f fix: change LiteLLM content and tool parameter handling
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
2025-11-12 09:23:00 -08:00
Ankur Sharma e2d3b2d862 feat: Added support for InOrder and AnyOrder match in ToolTrajectoryAvgScore Metric
Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 831413968
2025-11-12 09:10:34 -08:00
Google Team Member b2c8ba5806 chore: Defer import of live, Client and _transformers in google.genai
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
2025-11-11 23:56:20 -08:00
Google Team Member 37ee1869b5 fix: Enhance BigQuery Plugin Robustness and Schema Accuracy
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
2025-11-11 22:47:13 -08:00
Shangjie Chen a501c59ac4 feat: Support registering custom services from local files
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
2025-11-11 21:59:19 -08:00
George Weale 99fc17b336 feat: add adk folder manager and per agent local storage helpers
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
2025-11-11 21:38:51 -08:00
Google Team Member 3674fbbe8f fix: Update the retry_on_closed_resource decorator to retry on all errors
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
2025-11-11 18:44:18 -08:00
Liang Wu 999af55880 chore: Defer import of google.cloud.storage in GCSArtifactService
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
2025-11-11 17:02:20 -08:00
Liang Wu 22ca7eefc0 chore: Defer import of live, Client and _transformers in google.genai
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
2025-11-11 17:01:28 -08:00
Kathy Wu a550509441 fix: Update the retry_on_closed_resource decorator to retry on all errors
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
2025-11-11 16:57:25 -08:00
Google Team Member d85a301039 feat: Add support for passing request metadata in RemoteA2AAgent
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
2025-11-11 16:49:39 -08:00
Google Team Member 249216e890 feat: Add Graceful Plugin Shutdown to Runner
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
2025-11-11 13:05:03 -08:00
Hangfei Lin 01bac62f0c chore: Update agent instructions and retry limit in plugin_reflect_tool_retry sample
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
2025-11-11 10:52:44 -08:00
Hangfei Lin 01a0309f0a chore: Add Go ADK link to README
The README now includes a link to the `adk-go` GitHub repository.

Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 830971424
2025-11-11 10:21:36 -08:00
Google Team Member 824ab07212 fix: Let part converters also return multiple parts so they can support more usecases
PiperOrigin-RevId: 830882000
2025-11-11 06:15:00 -08:00
Catalin Lupuleti fd33610e96 test: add tests for max_query_result_rows in BigQuery tool config
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
2025-11-10 19:43:24 -08:00
Hangfei Lin 2b0f953255 feat: Add artifact metadata support and a new sample for context offloading
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
2025-11-10 14:10:10 -08:00
GitMarco27 74959414d8 feat: full async implementation of DatabaseSessionService
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
2025-11-10 11:18:02 -08:00
Shangjie Chen 2443a1b74f docs: Update adk cli help message regarding the update to SqliteSessionService
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 830521954
2025-11-10 11:09:57 -08:00
George Weale 7b87056dfa fix: adapt fixtures for pytest 9 rules
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 830493430
2025-11-10 10:06:12 -08:00
Amy Wu 7937e9ed40 fix: Use async with for API client in Vertex session management to ensure proper resource management
PiperOrigin-RevId: 830485639
2025-11-10 09:49:10 -08:00
George Weale c4858896ff fix: Update description for load_artifacts tool
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
2025-11-10 09:07:59 -08:00
George Weale 0db2041e1a fix: Correct FastAPI version constraint in toml
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
2025-11-10 08:58:15 -08:00
Jeff Bryner 352dd995e1 fix: Add required parameters with defaults if missing
Merge https://github.com/google/adk-python/pull/2054

fixes https://github.com/google/adk-python/issues/2053

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2054 from jeffbryner:fix-required-params dd75a0b5798792dccb1ca0ac0240ce0c0b1fad14
PiperOrigin-RevId: 830251203
2025-11-09 20:46:41 -08:00
Xuan Yang f31226ee92 docs: Update the error message for function parameter ToolContext not named as tool_context
Fixes https://github.com/google/adk-python/issues/1530

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 830248414
2025-11-09 20:35:28 -08:00
George Weale 93aad61198 fix: Safely handle FunctionDeclaration without a required attribute
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
2025-11-09 19:06:45 -08:00
Sanjay Siddharth MJ 2882995289 fix: Fixes DeprecationWarning when using send method
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
2025-11-09 16:00:43 -08:00
GenkiNoguchi a3b4ec69d8 feat: Add user_id property to ReadonlyContext
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
2025-11-09 14:51:52 -08:00
Max Ind 116b26c33e feat: add plugin for returning GenAI Parts from tools into the model request
Added to mitigate https://github.com/google/adk-python/issues/3064

Co-authored-by: Max Ind <maxind@google.com>
PiperOrigin-RevId: 830135940
2025-11-09 11:47:08 -08:00
Shangjie Chen e218254495 feat: Add SqliteSessionService and a migration script to migrate existing DB using DatabaseSessionService to SqliteSessionService
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
2025-11-08 21:19:38 -08:00
Wei Sun (Jack) 50ceda00cf docs(models): Updates BaseLlm#generate_content_async docstring with the expected behavior
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
2025-11-08 13:21:38 -08:00
Google Team Member 6b14f88726 feat: Refactor and Rename BigQuery Agent Analytics Plugin
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
2025-11-07 15:44:03 -08:00
GenkiNoguchi 42d4c4ed5f chore: Change live connection log level from info to debug
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
2025-11-07 15:20:10 -08:00
Google Team Member 34ea2edfd2 fix: Fixes a bug introduced by the underlying google genai library
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
2025-11-07 14:02:41 -08:00
Google Team Member 9e22cc4022 feat: Bigquery detect_anomalies tool results sort by timestamp for better visualization
Timestamp need to be ordered so that for better display and further visualization.

PiperOrigin-RevId: 829548481
2025-11-07 13:03:34 -08:00
Lê Nam Khánh 51dee43f08 docs: fix typos in some files
Merge https://github.com/google/adk-python/pull/3444

This PR fixes typos in the file file using codespell.

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3444 from khanhkhanhlele:Fix/typos/20251107165249 e9629a8c0255ddc0764cb0df7f36ebe61bd6515e
PiperOrigin-RevId: 829516217
2025-11-07 11:32:32 -08:00
George Weale e0e762598e docs: Use a trimmed ADK AgentConfig schema in Agent Builder Assistant
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
2025-11-07 11:26:18 -08:00
Henrique Cadioli 8f3c3bfda5 fix: cache canonical tools to avoid multiple calls when streaming
Merge https://github.com/google/adk-python/pull/3299
Fixes https://github.com/google/adk-python/issues/3237

Co-authored-by: Xuan Yang <xygoogle@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3299 from hcadioli:fix/cache-tools de02bd3e4533c3741edf05788a5e8b2d3d38bae4
PiperOrigin-RevId: 829499299
2025-11-07 10:51:32 -08:00
Kathy Wu 9761fc6bbb fix: Fix McpToolset hanging indefinitely
This fixes McpToolset from hanging indefinitely during a list_tools call (https://github.com/google/adk-python/issues/3084) by adding a timeout.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 829499276
2025-11-07 10:50:38 -08:00
Naofumi Yamada 0ccc43cf49 fix: Fix error when query job destination is None
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
2025-11-06 22:28:06 -08:00
Google Team Member a0cf97eba2 feat: Some small infra fixes to the gepa demo colab
PiperOrigin-RevId: 829240716
2025-11-06 20:44:25 -08:00
Google Team Member d118479ccf feat: Improve gepa voter agent demo colab
PiperOrigin-RevId: 829208761
2025-11-06 19:13:11 -08:00
Kathy Wu 8e0648df23 fix: Fix MCPToolset crashing with anyio.BrokenResourceError
Add error handling for broken resource error so that it retries. Fixes https://github.com/google/adk-python/issues/2769.

Co-authored-by: Kathy Wu <wukathy@google.com>
PiperOrigin-RevId: 829146121
2025-11-06 16:12:49 -08:00
Google Team Member c0be1df052 feat: set per-tool user agent in BQ calls and tool label in BQ jobs
This will help per tool usage for BigQuery tools.

PiperOrigin-RevId: 829142106
2025-11-06 16:01:50 -08:00
Google Team Member f1f44675e4 ADK changes
PiperOrigin-RevId: 829136628
2025-11-06 15:55:26 -08:00
Hangfei Lin f3d6fcf444 chore: Add debug logging for missing function call events
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
2025-11-06 12:20:36 -08:00
Liang Wu dd706bdc45 feat: Update conformance test CLI to handle long-running tool calls
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
2025-11-06 11:38:13 -08:00
Wei Sun (Jack) e511eb1f70 chore: Removes the unrealistic todo comment of visibility management
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 829041637
2025-11-06 11:36:49 -08:00
George Weale 7ea4aed35b fix: Add support for structured output schemas in LiteLLM models
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
2025-11-06 11:29:10 -08:00
Josh Soref d672349ddf chore: Fix spelling in tests
Merge https://github.com/google/adk-python/pull/3402

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

Co-authored-by: Liang Wu <wuliang@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3402 from jsoref:spelling-tests 3cf0439d0584e4557179c25596aadf3b5b7c3fa8
PiperOrigin-RevId: 829035089
2025-11-06 11:21:59 -08:00
Hangfei Lin 1819ecb4b8 fix: Improve handling of partial and complete transcriptions in live calls
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
2025-11-06 11:09:21 -08:00
Liang Wu 44d45fe9cd chore: Lazy load Vertex AI dependencies in ADK modules
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
2025-11-06 10:40:54 -08:00
Liang Wu 5f057498a2 chore: Lazy import DatabaseSessionService in the adk/sessions/ module
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
2025-11-06 10:24:43 -08:00
Krzysztof Czuszynski 8dd5a79b29 fix: Fix transcript finish
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
2025-11-06 09:29:12 -08:00
Google Team Member f167890d00 feat: Add documentation and instructions to help configure gepa experiments
PiperOrigin-RevId: 828911323
2025-11-06 05:31:24 -08:00
George Weale e3caf79139 feat: expose artifact URLs to the model when available
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
2025-11-05 22:17:37 -08:00
Hangfei Lin 52db15f133 fix: Remove unused _run_compaction_default method
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
2025-11-05 20:47:09 -08:00
Josh Soref e568558674 chore: Fix spelling in markdown files
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
2025-11-05 20:30:49 -08:00
Kapil Sachdeva d7521eb638 feat: Expose run_config of current invocation from ReadonlyContext
Merge https://github.com/google/adk-python/pull/3410

### Link to Issue or Description of Change

**1. Link to an existing issue (if applicable):**

- Closes: #3409

Co-authored-by: Hangfei Lin <hangfei@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3410 from ksachdeva:expose-runconfig b62b923df421f0bdc1c20948d16765c555c01cb8
PiperOrigin-RevId: 828738445
2025-11-05 19:47:11 -08:00
Shangjie Chen f511352508 chore: Clarify the usage of agent_state
Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 828733706
2025-11-05 19:30:58 -08:00
ananyablonko 0fccc7933a fix(core): ParallelAgent's branching with include_contents='none' may cause index out of range error
Merge https://github.com/google/adk-python/pull/2961

Fixes #2404

Consider code where a sub_agent somewhere under a ParallelAgent has include_contents='none'.
```python
import asyncio
import os
from typing import TypedDict
from dotenv import load_dotenv

from google.adk.agents import LlmAgent, ParallelAgent, SequentialAgent
from google.adk.runners import Runner
from google.adk.sessions import DatabaseSessionService, InMemorySessionService
from google.genai import types
import logging

USE_DB=False

load_dotenv()
logging.basicConfig(
    filename='log.log',
    level=logging.DEBUG
)
for logger_name in ["httpcore"]:
    logging.getLogger(logger_name).setLevel(logging.ERROR)

class AgentArgs(TypedDict):
    model: str
    instruction: str

class SessionArgs(TypedDict):
    user_id: str
    session_id: str

agent_args = AgentArgs(
    model="gemini-2.0-flash",
    instruction="Answer 'Ack' and nothing else."
)

session_args = SessionArgs(
    user_id="0",
    session_id="0"
)

app_name = "Test"

def create_agent_in_branch(i: int):
    agent_1 = LlmAgent(
        name=f"subagent_{i}_1",
        **agent_args
    )

    agent_2 = LlmAgent(
        name=f"subagent_{i}_2",
        include_contents='none',
        **agent_args
    )

    return SequentialAgent(
        name=f"agent_{i}",
        sub_agents=[agent_1, agent_2]
    )

root = ParallelAgent(
    name="root",
    sub_agents=[create_agent_in_branch(i) for i in range(1, 5)]
)

runner = Runner(
    agent=root,
    app_name=app_name,
    session_service=DatabaseSessionService(db_url=os.getenv("DB_URL", "")) if USE_DB else InMemorySessionService(),
)

async def main() -> None:
    try:
        await runner.session_service.delete_session(app_name=app_name, **session_args)
    except:
        pass
    await runner.session_service.create_session(app_name=app_name, **session_args)

    message = types.Content(role="user", parts=[types.Part(text=" ")])
    async for event in runner.run_async(**session_args, new_message=message):
        if event.is_final_response():
            print(((event.content or types.Content()).parts or [types.Part()])[0].text or "")

if __name__ == '__main__':
    asyncio.run(main())
```

The log here will often have one or more ```subagent_{i}_2``` not receive their prompts from ```subagent_{i}_1```.
This inconsistency is caused by the way ```include_contents='none'``` is implemented in flows/llm_flows/contents.py:328-356:

```python
    for i in range(len(events) - 1, -1, -1):
    event = events[i]
    if event.author == 'user' or _is_other_agent_reply(agent_name, event):
      return _get_contents(current_branch, events[i:], agent_name)

  return []
```

That is, we first find the most recent (other-agent / user) event, **even if it's not on our branch**, and then filter the remainder. Thus in the above example, we may sometimes filter out all events, when we expect to have the event of a previous agent in a ```SequentialAgent```.

The solution is to first filter events by branch, and only then search for the latest.

### TEST SUMMARY:
```
=================================================== short test summary info ===================================================
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[GOOGLE_AI-LoopAgent-LoopAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[GOOGLE_AI-google.adk.agents.LoopAgent-LoopAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[GOOGLE_AI-google.adk.agents.loop_agent.LoopAgent-LoopAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[GOOGLE_AI-ParallelAgent-ParallelAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[GOOGLE_AI-google.adk.agents.ParallelAgent-ParallelAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[GOOGLE_AI-google.adk.agents.parallel_agent.ParallelAgent-ParallelAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[GOOGLE_AI-SequentialAgent-SequentialAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[GOOGLE_AI-google.adk.agents.SequentialAgent-SequentialAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[GOOGLE_AI-google.adk.agents.sequential_agent.SequentialAgent-SequentialAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[VERTEX-LoopAgent-LoopAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[VERTEX-google.adk.agents.LoopAgent-LoopAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[VERTEX-google.adk.agents.loop_agent.LoopAgent-LoopAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[VERTEX-ParallelAgent-ParallelAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[VERTEX-google.adk.agents.ParallelAgent-ParallelAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[VERTEX-google.adk.agents.parallel_agent.ParallelAgent-ParallelAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[VERTEX-SequentialAgent-SequentialAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[VERTEX-google.adk.agents.SequentialAgent-SequentialAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_with_sub_agents[VERTEX-google.adk.agents.sequential_agent.SequentialAgent-SequentialAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_llm_agent_with_sub_agents[GOOGLE_AI-LlmAgent-LlmAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_llm_agent_with_sub_agents[GOOGLE_AI-google.adk.agents.LlmAgent-LlmAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_llm_agent_with_sub_agents[GOOGLE_AI-google.adk.agents.llm_agent.LlmAgent-LlmAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_llm_agent_with_sub_agents[VERTEX-LlmAgent-LlmAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_llm_agent_with_sub_agents[VERTEX-google.adk.agents.LlmAgent-LlmAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/agents/test_agent_config.py::test_agent_config_discriminator_llm_agent_with_sub_agents[VERTEX-google.adk.agents.llm_agent.LlmAgent-LlmAgent] - FileNotFoundError: Config file not found: C:\Users\AnanYablonko\AppData\Local\Temp\pytest-of-AnanYablonko\pytest-1\test_age...
FAILED tests/unittests/cli/utils/test_cli_tools_click.py::test_cli_run_invokes_run_cli[GOOGLE_AI] - AssertionError: assert 1 == 0
FAILED tests/unittests/cli/utils/test_cli_tools_click.py::test_cli_run_invokes_run_cli[VERTEX] - AssertionError: assert 1 == 0
FAILED tests/unittests/cli/utils/test_cli_tools_click.py::test_cli_eval_with_eval_set_file_path[GOOGLE_AI] - assert 0 == 1
FAILED tests/unittests/cli/utils/test_cli_tools_click.py::test_cli_eval_with_eval_set_file_path[VERTEX] - assert 0 == 1
FAILED tests/unittests/evaluation/test_local_eval_sets_manager.py::TestLocalEvalSetsManager::test_local_eval_sets_manager_update_eval_case_eval_set_not_found[GOOGLE_AI] - OSError: [Errno 22] Invalid argument: '<tests.unittests.evaluation.test_local_eval_sets_manager.TestLocalEvalSetsManager ob...
FAILED tests/unittests/evaluation/test_local_eval_sets_manager.py::TestLocalEvalSetsManager::test_local_eval_sets_manager_update_eval_case_eval_set_not_found[VERTEX] - OSError: [Errno 22] Invalid argument: '<tests.unittests.evaluation.test_local_eval_sets_manager.TestLocalEvalSetsManager ob...
FAILED tests/unittests/evaluation/test_local_eval_sets_manager.py::TestLocalEvalSetsManager::test_local_eval_sets_manager_delete_eval_case_eval_set_not_found[GOOGLE_AI] - OSError: [Errno 22] Invalid argument: '<tests.unittests.evaluation.test_local_eval_sets_manager.TestLocalEvalSetsManager ob...
FAILED tests/unittests/evaluation/test_local_eval_sets_manager.py::TestLocalEvalSetsManager::test_local_eval_sets_manager_delete_eval_case_eval_set_not_found[VERTEX] - OSError: [Errno 22] Invalid argument: '<tests.unittests.evaluation.test_local_eval_sets_manager.TestLocalEvalSetsManager ob...
FAILED tests/unittests/sessions/test_session_service.py::test_get_session_with_config[GOOGLE_AI-SessionServiceType.DATABASE] - OSError: [Errno 22] Invalid argument
FAILED tests/unittests/sessions/test_session_service.py::test_get_session_with_config[VERTEX-SessionServiceType.DATABASE] - OSError: [Errno 22] Invalid argument
================================= 34 failed, 4540 passed, 3044 warnings in 187.68s (0:03:07) ==================================
```

Co-authored-by: Wei Sun (Jack) <weisun@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2961 from ananyablonko:main b4a21adcd4231efeffd552a96734b2161b317e0a
PiperOrigin-RevId: 828700099
2025-11-05 17:41:35 -08:00
Lorenzo 63b69fbc0f fix(cli): Handle the case when OS doesn't support symlink for adk run
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
2025-11-05 17:09:51 -08:00
Josh Soref 1d80d32efc chore: Fix spelling in src
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
2025-11-05 16:59:10 -08:00
Google Team Member 48681cb31b chore: Returns agent state regardless if ctx.is_resumable
This allows state to be passing across agents

PiperOrigin-RevId: 828665491
2025-11-05 15:59:57 -08:00
Josh Soref 59d422ca21 chore: Fix spelling in contributing
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
2025-11-05 15:43:25 -08:00
Google Team Member a2ce34a0b9 feat: Migrate BigQuery logging to Storage Write API
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
2025-11-05 15:33:57 -08:00
Wei Sun (Jack) fa5c546a55 fix(tools): Add proper cleanup for AgentTool to prevent MCP session errors
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
2025-11-05 15:23:39 -08:00
Kathy Wu ee8106be77 fix: Fix error handling when MCP server is unreachable
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
2025-11-05 15:15:58 -08:00
George Weale 99ca6aa6e6 feat: add file-backed artifact service
- 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
2025-11-05 14:26:51 -08:00
George Weale d9ec07d39b docs: Improve Agent Builder Assistant schema reference for prompts
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
2025-11-05 14:23:18 -08:00
Josh Soref 2b31bd9414 chore: Fix spelling: provide
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
2025-11-05 13:40:17 -08:00
Google Team Member e02f177790 feat: Improve gepa tau-bench colab for external use
PiperOrigin-RevId: 828579343
2025-11-05 12:23:47 -08:00
Xuan Yang 9ec38c0d89 feat: Add on_model_error_callback in LlmAgent
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 828560608
2025-11-05 11:37:08 -08:00
Shangjie Chen d6b928bdf7 chore: Returns agent state regardless if ctx.is_resumable
This allows state to be passing across agents

Co-authored-by: Shangjie Chen <deanchen@google.com>
PiperOrigin-RevId: 828557989
2025-11-05 11:31:26 -08:00
Google Team Member 744f94f0c8 fix: Add None check for event in remote_a2a_agent.py
PiperOrigin-RevId: 828538350
2025-11-05 10:47:24 -08:00
Xuan Yang d8d7774f0f chore: Update v1.18.0 wheel and CHANGELOG.md
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 828533243
2025-11-05 10:35:33 -08:00
Hangfei Lin 082675546f chore: Stop logging the full content of LLM blobs
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
2025-11-05 10:12:07 -08:00
Hangfei Lin aa77834e2e chore: Update Gemini Live model names in live bidi streaming sample
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
2025-11-05 09:57:59 -08:00
Yeesian Ng 0b1784e0e4 fix: Update dependency version constraints to be based on PyPI versions
Co-authored-by: Yeesian Ng <ysian@google.com>
PiperOrigin-RevId: 828460860
2025-11-05 07:32:00 -08:00
Xuan Yang e01e54e9ee chore: Bumps version to v1.18.0 and updates CHANGELOG.md
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 828313025
2025-11-04 23:20:57 -08:00
Google Team Member 63353b2b74 feat: Refactor gepa sample code and clean-up user demo colab
PiperOrigin-RevId: 828293079
2025-11-04 22:16:55 -08:00
Nimantha Cooray 4284c61901 fix: agent evaluations detailed output rows wrapping issue
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
2025-11-04 20:40:45 -08:00
Hyeongjun Kang 0c49aef251 chore: correct typo in pyproject.toml (swtich → switch)
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
2025-11-04 18:30:22 -08:00
Yeesian Ng d4b2a8b49f feat: Add support for Vertex AI Express Mode when deploying to Agent Engine
Co-authored-by: Yeesian Ng <ysian@google.com>
PiperOrigin-RevId: 828178479
2025-11-04 16:24:07 -08:00
Google Team Member 033f5a5d3f feat: Add configuration options to BigQuery logging plugin
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
2025-11-04 16:06:49 -08:00
Kathy Wu 88032cf5c5 feat: Support MCP prompts
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
2025-11-04 15:48:21 -08:00
Kathy Wu 11571c37ab fix: Reduce logging spam for MCP tools without authentication
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
2025-11-04 15:34:24 -08:00
Hangfei Lin 432d30af48 chore: Add Community Repo section to README
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
2025-11-04 15:17:48 -08:00
Google Team Member 54db3d4434 fix: update the contribution analysis tool to use original write mode
PiperOrigin-RevId: 828126582
2025-11-04 14:05:28 -08:00
Kathy Wu 6e5c0eb6e0 feat: Add token usage to live events for bidi streaming
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
2025-11-04 14:01:25 -08:00
Eliza Huang 4f85e86fc3 feat: Add support for extracting cache-related token counts from LiteLLM usage
Closes #3049

Co-authored-by: Eliza Huang <heliza@google.com>
PiperOrigin-RevId: 828091671
2025-11-04 12:43:06 -08:00
Yifan Wang abdc2bb954 chore: update adk web for adk web builder: https://github.com/google/adk-web/pull/248
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 828061540
2025-11-04 11:27:48 -08:00
George Weale ce91a8ef73 fix: Pass drop_params to LiteLLM completion API
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
2025-11-04 11:19:58 -08:00
Shan Cao d4c63fc562 chore: Add model tracking to LiteLlm and introduce a LiteLLM with fallbacks demo
Related: #2292

Co-authored-by: Shan Cao <caoshan@google.com>
PiperOrigin-RevId: 828024955
2025-11-04 10:10:09 -08:00
George Weale e25beb4bce docs: Refine ADK triaging agent labeling guidelines and response format
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 828022792
2025-11-04 10:05:20 -08:00
George Weale 489c39db01 fix: Remove redundant format field from LiteLLM content objects
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
2025-11-04 09:44:38 -08:00
Google Team Member 38ea749c9c feat: Extend Bigquery detect_anomalies tool to support future data anomaly detection
ARIMA supports both historical data and future data anomaly detection. This CL add how the tool support future table anomaly detection.

PiperOrigin-RevId: 827803748
2025-11-03 23:02:02 -08:00
Haegyun Lee d2888a3766 fix: Fix typo in several files
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
2025-11-03 18:07:34 -08:00
Xuan Yang 6a94af24bf chore: Disable SetModelResponseTool workaround for Vertex AI Gemini 2+ models
Gemini models now [support Function calling being used together with structured output on Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#structured-output-bp).

Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 827709903
2025-11-03 17:12:01 -08:00
Yifan Wang 8b6ee576d5 chore: remove working_in_progress for agent builder endpoints
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 827698290
2025-11-03 16:37:38 -08:00
Haegyun Lee f81ebdb622 fix: Bug when callback_context_invocation_context is missing in GlobalInstructionPlugin
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
2025-11-03 15:54:54 -08:00
George Weale c33a680b54 docs: Add instructions to prevent tool hallucination
Co-authored-by: George Weale <gweale@google.com>
PiperOrigin-RevId: 827632446
2025-11-03 13:41:03 -08:00
Josh Soref aa1233608a chore: Fix spelling
Merge https://github.com/google/adk-python/pull/2447

This PR corrects misspellings identified by the [check-spelling action](https://github.com/marketplace/actions/check-spelling)

The misspellings have been reported at https://github.com/jsoref/adk-python/actions/runs/16840838898/attempts/1#summary-47711379253

The action reports that the changes in this PR would make it happy: https://github.com/jsoref/adk-python/actions/runs/16840839269/attempts/1#summary-47711380479

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.

I've included a couple of changes to make CI happy. Personally, I object to CI being in a state of "random drive by person who adds a blank line in the middle of a file must fix all the preexisting bugs in the file", but that appears to be the state for this repository.

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2447 from jsoref:spelling d85398e7fd154d124d477c6af6181481a01f34e0
PiperOrigin-RevId: 827629615
2025-11-03 13:33:53 -08:00
Google Team Member 8dff85099d fix: Support models slash prefix in model name extraction
Support "models/" prefix in model name extraction

PiperOrigin-RevId: 827557443
2025-11-03 10:32:49 -08:00
Xuan Yang 92a7d19573 fix: Undo adding MCP tools output schema to FunctionDeclaration
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 827557144
2025-11-03 10:31:58 -08:00
Kacper Jawoszek a02f321f1b chore(otel): Change default of trace_to_cloud to None for Agent Engine deploy
Also added --no-trace_to_cloud to allow for explicit disablement.

This is needed to distinguish between default-on telemetry and explicit disablement via old enable_tracing/trace_to_cloud flags. Same change was done to ADK templates - see https://github.com/googleapis/python-aiplatform/pull/5917/files#diff-54084046c0ff3ec289916eefbb00d04f797ebd02dc15b417fc4fc88137fd2123R439.

Co-authored-by: Kacper Jawoszek <jawoszek@google.com>
PiperOrigin-RevId: 827552868
2025-11-03 10:21:12 -08:00
G. Hussain Chinoy 308da620c1 docs: updates CONTRIBUTING.md
Merge https://github.com/google/adk-python/pull/2286

Clarity for statement, corrects misspelling

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2286 from ghchinoy:patch-1 f50d59858dee4c7412f108dcebbe05697491cdcc
PiperOrigin-RevId: 827541249
2025-11-03 09:54:31 -08:00
nikkie 2c6d6e1594 fix: fix typo for --save_session option in adk run --resume help
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
2025-11-02 21:23:39 -08:00
Jeroen Overschie 44aa82195a docs: fix spelling error in response_for_auth_required parameter docstring
Merge https://github.com/google/adk-python/pull/2680

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2680 from dunnkers:docs/fix-spelling-error-in-parameter-docstring 39782ac73381f6aa6b5392356eb9374b0680d611
PiperOrigin-RevId: 827163203
2025-11-02 08:56:00 -08:00
nikkie 4124f54a36 refactor: Remove unnecessary branching in run_cli
Merge https://github.com/google/adk-python/pull/2537

Streamlined code flow by removing redundant if/else logic

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2537 from ftnext:refactor-run-cli d799e17a7dd7beb0adecd0bd28237a5e09949a6c
PiperOrigin-RevId: 827153566
2025-11-02 08:04:56 -08:00
FingerLiu c4c127df23 fix: fix typo in local_eval_service.py
Merge https://github.com/google/adk-python/pull/2586

_perform_inference_sigle_eval_item -> _perform_inference_single_eval_item

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2586 from FingerLiu:main 78083cb5d4ba1cc90785ad5d727756d467737e08
PiperOrigin-RevId: 826666447
2025-10-31 16:21:25 -07:00
Ankur Sharma b1ff85fb23 chore: Add support for specifying logging level for adk eval cli command
One can now control the logging levels for adk eval cli commands.

Co-authored-by: Ankur Sharma <ankusharma@google.com>
PiperOrigin-RevId: 826654122
2025-10-31 15:41:07 -07:00
Kathy Wu e8526f7e06 fix: Fix credential manager so that it supports the ServiceAccountCredentialExchanger
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
2025-10-31 14:55:06 -07:00
Yifan Wang a0df75b6fa chore: Add support for reversed proxy in adk web, users can use an optional param --root_path for proxy's path
Co-authored-by: Yifan Wang <wanyif@google.com>
PiperOrigin-RevId: 826632932
2025-10-31 14:37:26 -07:00
Lavi Nigam 0487eea2ab feat: add run_debug() helper method for quick agent experimentation
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
2025-10-31 13:28:02 -07:00
Google Team Member 0b56f2287b refactor(bigquery): Remove dataset_id from logging schema
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
2025-10-31 12:57:54 -07:00
Dongyu Jia 156d235479 feat: Allow injecting a custom Runner into agent_to_a2a
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
2025-10-31 09:54:59 -07:00
Dongyu Jia 338c3c89c6 fix: Add example and fix for loading and upgrading old ADK session databases
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
2025-10-31 09:47:53 -07:00
Eliza Huang a2c6a8a85c feat: Expose the Python code run by the code interpreter in the logs
Co-authored-by: Eliza Huang <heliza@google.com>
PiperOrigin-RevId: 826521391
2025-10-31 09:38:53 -07:00
Google Team Member 546c2a6816 feat: Remove custom polling logic for Vertex AI Session Service since LRO polling is supported in express mode
PiperOrigin-RevId: 826226731
2025-10-30 16:13:43 -07:00
Ayush Agrawal dea7668d1a chore: Allow google-cloud-storage >=3.0.0
Fixes #3012

Co-authored-by: Ayush Agrawal <ayushagra@google.com>
PiperOrigin-RevId: 826207388
2025-10-30 15:21:50 -07:00
Ankur Sharma 5cb35db921 chore: Avoid rendering empty columns as part of detailed results rendering of eval results
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
2025-10-30 15:08:07 -07:00
Kevin Qian b8a2b6c570 fix: include delimiter when matching events from parent nodes in content processor
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
2025-10-30 14:26:39 -07:00
Google Team Member 2274c4f304 feat: Add "final_session_state" to the EvalCase data model
This will allow setting a golden expectation on the session state for agents that will modify the states.

PiperOrigin-RevId: 826166904
2025-10-30 13:38:27 -07:00
Wei Sun (Jack) 610e219a9f ci: Fixes the copybara-pr-handler.yml file location, it should be under workflow folder
Co-authored-by: Wei Sun (Jack) <weisun@google.com>
PiperOrigin-RevId: 826143689
2025-10-30 12:37:56 -07:00
Jaroslav Pantsjoha 34d9b53f37 feat: Enhance error messages for tool and agent not found errors
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
2025-10-30 12:08:13 -07:00
Ayush Agrawal 5eca72f9bf fix: Correct message part ordering in A2A history
Merges test case from https://github.com/google/adk-python/pull/3262

Fixes: #3260

Co-authored-by: Ayush Agrawal <ayushagra@google.com>
PiperOrigin-RevId: 826119626
2025-10-30 11:36:38 -07:00
Shubham Saboo b0017aed44 chore: Revise README for clarity and consistency
Merge https://github.com/google/adk-python/pull/3335

Updated terminology in README for clarity and consistency.

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3335 from Shubhamsaboo:patch-1 57d574e2e28c539e97fcb7f5d82bc1d00ca7149e
PiperOrigin-RevId: 826105701
2025-10-30 11:02:27 -07:00
George Weale 1e6a9daa63 fix: Change instruction insertion to respect tool call/response pairs
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
2025-10-30 09:54:49 -07:00
Eliza Huang d3796f9b33 feat: Add example for using ADK with Fast MCP sampling
Close #2893

Co-authored-by: Eliza Huang <heliza@google.com>
PiperOrigin-RevId: 826070077
2025-10-30 09:39:36 -07:00
Wei Sun (Jack) 9704d27dfb ci: Add a github action to automatically close the PR imported and committed by Copybara
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
2025-10-30 09:09:19 -07:00
Ieva Grublyte ec86608734 docs: Add sample agent to test support of output_schema, tools and subagents at the same time for gemini model
Co-authored-by: Ieva Grublyte <ievagrublyte@google.com>
PiperOrigin-RevId: 826006607
2025-10-30 06:35:09 -07:00
Ieva Grublyte c0892c725c chore: remove legacy validation that forbids co-exist of agent transfer and output_schema. Closes #3318
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
2025-10-30 06:06:26 -07:00
Ayam ce8f674a28 fix: Allow LLM request to override the model used in the generate content async method in LiteLLM
Merge https://github.com/google/adk-python/pull/3066

Close #3065

Co-authored-by: Raman Mangla <ramanmangla@google.com>
PiperOrigin-RevId: 825880794
2025-10-29 23:34:33 -07:00
Xuan Yang 3814d8b80f docs: Update agent builder assistant to query knowledge base through HTTP instead of a2a
Co-authored-by: Xuan Yang <xygoogle@google.com>
PiperOrigin-RevId: 825848638
2025-10-29 21:32:48 -07:00
hung12ct fc15c9a0c3 fix: Update DynamicPickleType to support MySQL dialect
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
2025-10-29 20:39:58 -07:00
Eliza Huang f9569bbb1a fix: Enable usage metadata in LiteLLM streaming
Closes #3181

Co-authored-by: Eliza Huang <heliza@google.com>
PiperOrigin-RevId: 825833660
2025-10-29 20:37:54 -07:00
Eliza Huang 01b48c09ad feat: Add example demonstrating JSON passing between agents
Co-authored-by: Eliza Huang <heliza@google.com>
PiperOrigin-RevId: 825831151
2025-10-29 20:29:45 -07:00
Eliza Huang 71aa5645f6 fix: Propagate LiteLLM finish_reason to LlmResponse for use in callbacks
Closes #3114.

Co-authored-by: Eliza Huang <heliza@google.com>
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3319 from lizzij:fix/litellm-finish-reason-3109 da6ed0aec514231fc274fee744f885ae95b9d45c
PiperOrigin-RevId: 825783229
2025-10-29 17:55:03 -07:00
Dongyu Jia 64294572c1 feat: Add get_job_info tool to BigQuery toolset
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
2025-10-29 16:46:31 -07:00
Ankur Sharma 72a8d8d85b fix: Session input file are required for creating an eval case
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
2025-10-29 15:53:45 -07:00
Hangfei Lin b23eed6a85 feat: Remove @experimental from App class
This change marks the `App` class as no longer experimental.

Co-authored-by: Hangfei Lin <hangfei@google.com>
PiperOrigin-RevId: 825739749
2025-10-29 15:45:56 -07:00
Google Team Member 9014a849ea feat: Add api key argument to Vertex Session and Memory services for Express Mode support
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
2025-10-29 14:54:12 -07:00
Jack Sun d45b31fb45 chore: Ignore AI coding tool project-specific configs in .gitignore
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
2025-10-29 13:24:15 -07:00
Google Team Member 04dbc42e50 feat: Improve Tau-bench ADK colab stability
PiperOrigin-RevId: 825675599
2025-10-29 13:08:12 -07:00
Google Team Member 592c5d870e feat: Add initial colab to run GEPA on Tau-bench with ADK
PiperOrigin-RevId: 825675276
2025-10-29 13:07:24 -07:00
Google Team Member c0c67c8698 feat: Add ADK-based agent factory for Tau-bench
PiperOrigin-RevId: 825674874
2025-10-29 13:06:24 -07:00
Google Team Member 87f415a7c3 feat: Add util to run ADK LLM Agent with simulation environment
PiperOrigin-RevId: 825674499
2025-10-29 13:05:33 -07:00
Google Team Member e7f7705eba ADK changes
PiperOrigin-RevId: 825644096
2025-10-29 11:52:10 -07:00
Wei Sun (Jack) 2216fe7c04 docs: Update AGENTS.md with latest development guidelines and make it general for all AI coding tools
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
2025-10-29 11:14:48 -07:00
George Weale 0ce2d564f2 chore: Update agent triaging rules and owners
PiperOrigin-RevId: 825572235
2025-10-29 09:06:12 -07:00
Vishwa Murugan c8e5340962 fix: Propagate MCP tools output schema to FunctionDeclaration
PiperOrigin-RevId: 825380145
2025-10-28 23:03:47 -07:00
Google Team Member 1ee93c8bcb fix: do not consider events with state delta and no content as final response
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
2025-10-28 19:36:34 -07:00
Kevin Qian 6bdac02dfc fix: do not consider events with state delta and no content as final response
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
2025-10-28 17:41:03 -07:00
Omar Elcircevi 74a3500fc5 fix: #3036 parameter filtering for CrewAI functions with **kwargs
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
2025-10-28 17:30:59 -07:00
Ayush Agrawal 15afbcd158 feat: Add ADK_DISABLE_LOAD_DOTENV environment variable that disables automatic loading of .env when running ADK cli, if set to true or 1
Fixes #3228

PiperOrigin-RevId: 825273905
2025-10-28 17:25:40 -07:00
Ayush Agrawal ee8acc58be chore: Allow tenacity 9.0.0
Fixes #2962

PiperOrigin-RevId: 825269865
2025-10-28 17:13:05 -07:00
Xinran (Sherry) Tang 420de9c5be test: Add a test case for resuming any invocation
PiperOrigin-RevId: 825266283
2025-10-28 17:03:07 -07:00
Ayush Agrawal 2f72ceb49b chore: Do not treat FinishReason.STOP as error case for LLM responses containing candidates with empty contents
Fixes #2905

PiperOrigin-RevId: 825263302
2025-10-28 16:54:50 -07:00
Artem Oroberts 8eeff35b35 feat: Demonstrate CodeExecutor customization for environment setup
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
2025-10-28 15:53:03 -07:00
Artem Oroberts edfe553942 feat: Add sample agent for VertexAiCodeExecutor
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
2025-10-28 15:52:14 -07:00
Ankur Sharma 1aa9bb13b3 chore: Update vertex ai in example store and rag retrieval to use proxy
PiperOrigin-RevId: 825237803
2025-10-28 15:46:38 -07:00
Wei Sun (Jack) 61adfcd69a refactor: Adds a util method to check the enablement of any env variable
PiperOrigin-RevId: 825199260
2025-10-28 14:18:45 -07:00
Liang Wu 971eafab96 feat: Add crewai[tools] to pyproject.toml test section
This dependency is added for Python versions 3.10 and above to support CrewaiTool unit tests. https://github.com/google/adk-python/actions/runs/18813223838/job/53801335597?pr=3037.

PiperOrigin-RevId: 825189153
2025-10-28 13:49:01 -07:00
Google Team Member 9851340ad1 feat: Add Bigquery detect_anomalies tool
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
2025-10-28 13:30:04 -07:00
George Weale 74d8361a7e fix: Add a fallback user message to LiteLLM requests if the last user message is empty
Related to #3255
Close #2560

PiperOrigin-RevId: 825143315
2025-10-28 11:56:47 -07:00
SOORAJ TS 240ef5beea feat: Added support for enums as arguments for function tools (#3088)
* 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>
2025-10-28 10:35:02 -07:00
Ankur Sharma b17c8f19e5 chore: Marked expected_invocation as optional field on evaluator interface
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
2025-10-28 10:27:47 -07:00
Shangjie Chen 9ab17f2afd fix: Yield the long running tool response before pausing execution
PiperOrigin-RevId: 825056377
2025-10-28 08:41:47 -07:00
Wei Sun (Jack) 86f01550bd docs: Fixes null check for reflect_retry plugin sample
PiperOrigin-RevId: 824836190
2025-10-27 22:13:06 -07:00
Hoonji Baek 6c3882f2d6 fix: Creates evalset directory on evalset create
PiperOrigin-RevId: 824746602
2025-10-27 17:26:32 -07:00
Google Team Member 87dcb3f7ba feat: Add ApigeeLlm as a model that let's ADK Agent developers to connect with an Apigee proxy
PiperOrigin-RevId: 824712152
2025-10-27 15:53:33 -07:00
Ankur Sharma 00d147d62f fix: check if eval config file exists
PiperOrigin-RevId: 824709118
2025-10-27 15:45:14 -07:00
Google Team Member b7dbfed4a3 feat: Add BigQueryLoggingPlugin for event logging to BigQuery
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
2025-10-27 15:30:56 -07:00
George Weale 0a87e02ffd fix: Rename agent config files to match the agent name
PiperOrigin-RevId: 824702674
2025-10-27 15:27:45 -07:00
George Weale 19f52467db docs: Update ADK agent builder instructions for model callback signatures
PiperOrigin-RevId: 824690587
2025-10-27 14:58:32 -07:00
George Weale 1ca82068fd docs: Automatically create __init__.py files when writing Python files
PiperOrigin-RevId: 824690193
2025-10-27 14:57:34 -07:00
Marlin Ranasinghe ab00c41fc9 fix: nullable types with gen ai bump
Merge https://github.com/google/adk-python/pull/3280

Fixes: #3281
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3280 from MarlzRana:marlzrana/fix-nullable-types-w-gen-ai-bump ad28b82cbdbb7980406086787e098bbe6478a354
PiperOrigin-RevId: 824659954
2025-10-27 13:43:50 -07:00
Shangjie Chen e194ebb33c feat: Implement artifact_version related methods in GcsArtifactService
PiperOrigin-RevId: 824646770
2025-10-27 13:13:07 -07:00
Google Team Member 1a4261ad4b fix: Fix issue with MCP tools throwing an error
Fixes: https://github.com/google/adk-python/issues/3082
PiperOrigin-RevId: 824620839
2025-10-27 12:08:43 -07:00
Xuan Yang 36ca4f1204 feat: Add on_tool_error_callback in LlmAgent
PiperOrigin-RevId: 824598502
2025-10-27 11:16:36 -07:00
Google Team Member 496f8cd6bb fix: output file uploading to artifact service should handle both base64 encoded and raw bytes
PiperOrigin-RevId: 824590321
2025-10-27 10:58:39 -07:00
Shangjie Chen f7e2a7a40e chore: Make VertexAiSessionService fully asynchronous
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
2025-10-27 10:19:25 -07:00
Liang Wu 48ddd07894 chore:clarify the behavior of disallow_transfer_to_parent
The original description is not clear enough and can create confusion like https://github.com/google/adk-python/issues/3081.

PiperOrigin-RevId: 824564227
2025-10-27 10:01:21 -07:00
Wei Sun (Jack) e0e5384e33 chore: Limits fastapi to <0.119, so that swagger api can still render
Temp workaround for #3173.

PiperOrigin-RevId: 824279228
2025-10-26 16:44:27 -07:00
Wei Sun (Jack) 16d4b9acca docs: Revise BaseAgent.after_agent_callback to be more clear
Clarify the behavior raised in #3266

PiperOrigin-RevId: 824273003
2025-10-26 16:10:42 -07:00
Max Ind e6f7363220 fix: set execute_tool {tool.name} span attributes even when exception occurs during tool's execution
PiperOrigin-RevId: 824165197
2025-10-26 06:07:25 -07:00
Google Team Member 5d9a7e7f79 feat: enable persistent browser sessions in the computer use sample
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
2025-10-24 19:15:10 -07:00
George Weale f8a9672b38 docs: Make sure LlmAgent as the immutable root agent in ADK configurations
PiperOrigin-RevId: 823699363
2025-10-24 16:10:24 -07:00
Kathy Wu fb96d17230 fix: Fix import for live bidi streaming single agent
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
2025-10-24 14:17:04 -07:00
Keyur Joshi 54c4ecc733 feat: Adds LLM-Backed User Simulator
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
2025-10-24 09:24:12 -07:00
Shangjie Chen 97a224fe46 chore: Clean up rag memory dependencies
PiperOrigin-RevId: 823556599
2025-10-24 09:19:49 -07:00
Google Team Member 64d9d6909c chore: Remove rogue print statement from agent_evaluator.py
PiperOrigin-RevId: 823552039
2025-10-24 09:06:06 -07:00
Hangfei Lin d767fccd5b chore: Add Community Events section to README
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
2025-10-23 21:10:48 -07:00
George Weale d193c396d6 docs: Add root agent requirement to instructions so it does not create workflow agents as root agent
PiperOrigin-RevId: 823256724
2025-10-23 17:46:11 -07:00
George Weale 53209f1bb9 docs: Clarify research tool instructions in YAML agent
PiperOrigin-RevId: 823255928
2025-10-23 17:43:20 -07:00
Xuan Yang 0d0fb4d034 ci: Remove reviewer assignment in the PR triaging agent
PiperOrigin-RevId: 823255296
2025-10-23 17:40:57 -07:00
George Weale 0660779ff0 docs: Update agent builder instructions to restrict fields on workflow agents
PiperOrigin-RevId: 823254695
2025-10-23 17:39:07 -07:00
Al Duncanson 0dbfb43052 fix: Update _evaluate_single_inference_result documentation
Merge https://github.com/google/adk-python/pull/3123

Update `_evaluate_single_inference_result` documentation

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3123 from alDuncanson:spelling-fix b7bb4d4180a481794a42a60817536e426e55cdb3
PiperOrigin-RevId: 823193022
2025-10-23 14:39:22 -07:00
Ankur Sharma bb32a6356c chore: Adding traceback logging to inference step of eval
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
2025-10-23 14:05:06 -07:00
Google Team Member ba631764a5 feat: Introduce custom_metadata field to run_config and propagate a2a request metadata to that field
PiperOrigin-RevId: 823066539
2025-10-23 09:14:19 -07:00
Ankur Sharma 955632ce2c feat:Allow agent evaluation from modules ending in ".agent"
PiperOrigin-RevId: 822888194
2025-10-22 23:11:48 -07:00
Ankur Sharma 6d4d72a499 chore: Update vertexai & rouge scorer dependencies in eval to use a proxy
PiperOrigin-RevId: 822881672
2025-10-22 22:44:53 -07:00
Vrajesh Babu A V 45a2168e0e chore: Adds a new sample agent that demonstrates how to integrate PostgreSQL databases using the Model Context Protocol (MCP)
## 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
2025-10-22 21:44:25 -07:00
George Weale 9cf7ab11a8 docs: Update agent builder instructions for clarity and best practices for ADK specific requirements
PiperOrigin-RevId: 822862453
2025-10-22 21:31:40 -07:00
Hangfei Lin 055e86a9d4 chore: Update ADK README with new features
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
2025-10-22 20:36:30 -07:00
Hangfei Lin 33fd712e29 chore: Remove community call announcement from README
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
2025-10-22 20:21:55 -07:00
Ankur Sharma 23092a273a feat: Consolidate external dependencies in a single place
PiperOrigin-RevId: 822771891
2025-10-22 15:55:33 -07:00
George Weale 4c58b767e5 docs: Update ADK Agent Builder Assistant instructions for workflow tools
PiperOrigin-RevId: 822756480
2025-10-22 15:11:16 -07:00
Google Team Member c426c48005 No public description
PiperOrigin-RevId: 822754668
2025-10-22 15:07:00 -07:00
George Weale f1e01ea4b0 docs: Update ADK Agent Builder Assistant instructions and clarified built-in tool naming
PiperOrigin-RevId: 822752065
2025-10-22 14:59:50 -07:00
George Weale c9647f3536 docs: Update agent builder instructions to require explicit agent_class
PiperOrigin-RevId: 822742468
2025-10-22 14:31:32 -07:00
Xuan Yang e28d3c55f8 chore: Add a pull request template
PiperOrigin-RevId: 822736669
2025-10-22 14:15:18 -07:00
Liang Wu 3ee1cd24db chore:Update conformance create command to record in documentation
PiperOrigin-RevId: 822736103
2025-10-22 14:14:06 -07:00
Hangfei Lin 91cc03e96f chore: Bump ADK version to 1 17 0
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
2025-10-22 14:01:26 -07:00
Kathy Wu d8c66fe688 fix: Update the saving artifact text for BuiltInCodeExecutor to be more human readable
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
2025-10-22 13:57:41 -07:00
Liang Wu c6cf11cb74 chore:Rename conformance create command to record
PiperOrigin-RevId: 822708044
2025-10-22 13:03:37 -07:00
Yifan Wang 2724819622 chore: update adk web, fixing cursor color, and thought bubble
PiperOrigin-RevId: 822693836
2025-10-22 12:27:28 -07:00
Alexey Guseynov 2f4f5611bd fix:Remove unnecessary Aclosing
PiperOrigin-RevId: 822496695
2025-10-22 02:40:07 -07:00
Wei Sun (Jack) 4df926388b fix: Returns dict as result from McpTool
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
2025-10-22 00:58:04 -07:00
Wei Sun (Jack) d4dc645478 chore: Fixes MCPToolset --> McpToolset in various places
PiperOrigin-RevId: 822377517
2025-10-21 19:42:37 -07:00
Wei Sun (Jack) 7d5c6b9acf fix: Fixes the identity prompt to be one line and add ending period after description statement
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
2025-10-21 18:31:48 -07:00
Yifan Wang aab2504ebd chore: update adk web
PiperOrigin-RevId: 822341297
2025-10-21 17:31:20 -07:00
Shangjie Chen 391628fcdc feat: Add a service registry to provide a generic way to register custom service implementations to be used in FastAPI server
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
2025-10-21 15:58:51 -07:00
Luis Pabon 409df1378f feat: Granular Per Agent Speech Configuration
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
2025-10-21 15:44:00 -07:00
Shangjie Chen 2a901d12f4 chore: Raise AlreadyExistsError when trying to create a resource with same ID
Move the dedupe logic into session service so that the internal error can be surfaced to client

PiperOrigin-RevId: 822294430
2025-10-21 15:11:33 -07:00
Xuan Yang c850da3a07 fix: Fix the broken langchain importing caused their 1.0.0 release
PiperOrigin-RevId: 822279014
2025-10-21 14:30:34 -07:00
Parham MohammadAlizadeh ed37e343f0 feat(tools): support additional headers for google api toolset #non-breaking
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
2025-10-21 14:16:37 -07:00
Kathy Wu ce3418a69d fix: Fix BuiltInCodeExecutor so that it can support visualizations
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
2025-10-21 13:06:43 -07:00
George Weale fe1fc75c15 chore: Improve hint message in agent loader
PiperOrigin-RevId: 822216833
2025-10-21 11:54:32 -07:00
George Weale dc4975dea9 fix: relax runner app-name enforcement
- 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
2025-10-21 11:30:21 -07:00
Google Team Member aeaec859bf feat: Adds Static User Simulator and User Simulator Provider
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
2025-10-21 11:15:11 -07:00
Jaroslav Pantsjoha 4a842c5a13 fix(cli): Improve error message when adk web is run in wrong directory
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
2025-10-21 10:47:30 -07:00
Wei Sun (Jack) 0bdba30263 docs: format README.md for samples
PiperOrigin-RevId: 822180731
2025-10-21 10:35:43 -07:00
Shangjie Chen 6a5eac0bdc feat: Allow passing extra kwargs to create_session of VertexAiSessionService
This can be used to set ttl and other configs.

PiperOrigin-RevId: 821782343
2025-10-20 13:34:07 -07:00
ejfn 0b73a6937b fix: Handle App objects in eval and graph endpoints
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
2025-10-20 12:11:26 -07:00
Google Team Member ee39a89110 feat: introduces a new AgentEngineSandboxCodeExecutor class that supports executes agent generated code
The AgentEngineSandboxCodeExecutor uses the Vertex AI Code Execution Sandbox API to execute code

PiperOrigin-RevId: 821699641
2025-10-20 10:14:34 -07:00
Shangjie Chen d327538724 chore: Throw 409 already exist error when trying to create a session with existing id
Resolves https://github.com/google/adk-python/issues/2950

PiperOrigin-RevId: 821362008
2025-10-19 11:21:36 -07:00
Google Team Member a5b742b360 feat: introduces a new AgentEngineSandboxCodeExecutor class that supports executes agent generated code
The AgentEngineSandboxCodeExecutor uses the Vertex AI Code Execution Sandbox API to execute code

PiperOrigin-RevId: 821197794
2025-10-18 20:24:04 -07:00
Wei Sun (Jack) af74eba695 test: Skips test_langchain_tool.py temporarily after their new 1.0.0 release breaks existings deps of langchain
PiperOrigin-RevId: 820875043
2025-10-17 16:53:11 -07:00
Google Team Member dbd818be0b feat: introduces a new AgentEngineSandboxCodeExecutor class that supports executes agent generated code
The AgentEngineSandboxCodeExecutor uses the Vertex AI Code Execution Sandbox API to execute code

PiperOrigin-RevId: 820854185
2025-10-17 15:42:24 -07:00
Xiang (Sean) Zhou a2d9f13fa1 chore: Add span for context caching handling and new cache creation
PiperOrigin-RevId: 820852233
2025-10-17 15:37:35 -07:00
Wei Sun (Jack) 0df67599c0 chore: Checks gemini version for 2 and above for gemini-builtin tools
PiperOrigin-RevId: 820848897
2025-10-17 15:27:47 -07:00
Shangjie Chen 8b3ed059c2 chore: Refactor and fix state management in the session service
Also refactoring the test cases to focus on the expected behaviors

PiperOrigin-RevId: 820734484
2025-10-17 10:04:36 -07:00
Ankur Sharma cf3403231d chore: Fix evaluation test cases to only use pytest features
PiperOrigin-RevId: 820700378
2025-10-17 08:25:17 -07:00
Shangjie Chen 9dce06f9b0 feat: Add rewind_async to support rewinding the session to before a previous invocation
PiperOrigin-RevId: 820552460
2025-10-16 23:24:40 -07:00
George Weale 307896aece fix: Exclude additionalProperties from Gemini schemas
PiperOrigin-RevId: 820542466
2025-10-16 22:40:43 -07:00
Kathy Wu 6dcbb5aca6 feat: Support dynamic per-request headers in MCPToolset
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
2025-10-16 15:12:43 -07:00
Xiang (Sean) Zhou 2a8fdd94e1 chore: Add computer use sample agent
PiperOrigin-RevId: 820407078
2025-10-16 14:59:27 -07:00
Xuan Yang 37a153ef94 ci: Fix the logs importing for PR triaging agent
PiperOrigin-RevId: 820395414
2025-10-16 14:27:18 -07:00
Giovanni Galloro ce4638651f docs: Bump models in llms and llms-full to Gemini 2.5
Merge https://github.com/google/adk-python/pull/3166

COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3166 from ggalloro:model-updates e741c8b266ef8cd7def203f94e8d9f8608c06685
PiperOrigin-RevId: 820381464
2025-10-16 13:53:45 -07:00
Doug Gebert e6e2767c39 chore: Update gemini_llm_connection.py - typo spelling correction
Merge https://github.com/google/adk-python/pull/3168

Fixed misspelling on line 228 from:
- logger.info('Redeived session...

To:
- logger.info('Received session...
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/3168 from DHHHG:patch-1 90b76d72ba474cd0092b2cc8d955b918c18d05bd
PiperOrigin-RevId: 820369618
2025-10-16 13:23:58 -07:00
Kacper Jawoszek e50f05a9fc feat(otel): env variable for disabling llm_request and llm_response in spans
The default without the variable set is to keep the content in spans to keep backward compatible behavior for existing users.

This allows to enable tracing without potential PII data from request and response. Google GenAI instrumentation lib requires an explicit opt-in to enable request and response content - see https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation-genai/opentelemetry-instrumentation-google-genai#enabling-message-content.

PiperOrigin-RevId: 820351154
2025-10-16 13:07:27 -07:00
Xuan Yang 9dc00360e3 ci: Add state info for PR triaging agent
PiperOrigin-RevId: 820340584
2025-10-16 13:07:18 -07:00
Google Team Member 5a543c00df feat: implement new methods in in-memory artifact service
* save_artifact with custom_metadata
* list_artifact_versions
* get_artifact_version

PiperOrigin-RevId: 820321444
2025-10-16 13:07:09 -07:00
Alexey Guseynov 1e1d63f34c fix: Internal change
PiperOrigin-RevId: 820159440
2025-10-16 13:07:00 -07:00
Xuan Yang f51380f9ea feat: Extend ReflectAndRetryToolPlugin to support hallucinating function calls
PiperOrigin-RevId: 820051762
2025-10-16 13:06:51 -07:00
Xuan Yang 3734ceaa6c fix: Use the agent's model when creating Google search agent tool
PiperOrigin-RevId: 819980797
2025-10-16 13:06:41 -07:00
Google Team Member 86097afe49 feat: Update AgentEvaluator to handle async ADK agent definitions
AgentEvaluator should recognize root_agent and get_agent_async as valid structures for ADK agent definitions.

PiperOrigin-RevId: 819976635
2025-10-16 13:06:31 -07:00
Google Team Member a17f3b2e6d feat: Allow custom request and event converters in A2aAgentExecutor
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
2025-10-16 13:06:21 -07:00
Shangjie Chen 6ab1498aa0 fix: Add usage_metadata and citation_metadata to DatabaseSessionService
PiperOrigin-RevId: 819900773
2025-10-16 13:05:52 -07:00
Google Team Member 2424d6a3b1 feat: Reorder create_time and mime_type to ArtifactVersion
Before: http://sponge2/ba05f9ac-c13d-43b6-bb8a-3e1b029cc705(failed)
After: http://sponge2/a623ba76-62c1-4d17-b4b6-22044333a801
PiperOrigin-RevId: 819896989
2025-10-15 13:46:12 -07:00
Lin Nikaido 36c96ec5b3 fix: #2883 pickle data was truncated error in database session using MySql
Merge https://github.com/google/adk-python/pull/2884

closes: #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
2025-10-15 13:33:22 -07:00
Shangjie Chen a985cc38ec feat: Support return all sessions when user id is none
PiperOrigin-RevId: 819884236
2025-10-15 13:14:24 -07:00
machache b650181384 feat: add support for ContetxtWindowCompressionConfig in RunConfig
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
2025-10-15 12:00:21 -07:00
Kathy Wu 78e74b5bf2 feat: Add require_confirmation param for MCP tool/toolset
This allows users to require human approval for using MCP tools.

PiperOrigin-RevId: 819800747
2025-10-15 09:58:31 -07:00
Ankur Sharma d82c492140 chore: Remove deprecated convert_session_to_eval_format function
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
2025-10-14 22:37:49 -07:00
Xuan Yang 05aa3fa38b fix: Remove the PR triaging agent's dependence on "bot triaged" label
PiperOrigin-RevId: 819427872
2025-10-14 15:35:59 -07:00
Google Team Member f9c09ef075 feat: Support returning all sessions when user_id is none in the request
resolves https://github.com/google/adk-python/issues/3154

PiperOrigin-RevId: 819417330
2025-10-14 15:10:41 -07:00
Shangjie Chen 141318f775 feat: Support returning all sessions when user_id is none in the request
resolves https://github.com/google/adk-python/issues/3154

PiperOrigin-RevId: 819401023
2025-10-14 14:30:47 -07:00
Google Team Member 85c95a8cbf feat: Add create_time and mime_type to ArtifactVersion
PiperOrigin-RevId: 819396924
2025-10-14 14:21:02 -07:00
Hangfei Lin cb6d583cad chore: Add RSVP link to ADK Community Call
This change adds a link to a Qualtrics form for RSVPing to the ADK Community Call in the README.

PiperOrigin-RevId: 819376219
2025-10-14 13:36:33 -07:00
Shangjie Chen 2c7a342593 feat: Add create_time and mime_type to ArtifactVersion
PiperOrigin-RevId: 819372593
2025-10-14 13:29:24 -07:00
Joseph Pagadora 9fbed0b15a fix: Overall eval status should be NOT_EVALUATED if no invocations were evaluated
PiperOrigin-RevId: 819322513
2025-10-14 11:36:33 -07:00
Xuan Yang bae21027d9 chore: Disable the scheduled execution for issue triage workflow
PiperOrigin-RevId: 819312327
2025-10-14 11:15:12 -07:00
George Weale 89344da813 chore: Update agent builder instructions and remove run command details
PiperOrigin-RevId: 819299339
2025-10-14 10:46:53 -07:00
Xiang (Sean) Zhou d22b8bf890 chore: Clarify how to use adk built-in tool in instruction
PiperOrigin-RevId: 818987709
2025-10-13 21:43:37 -07:00
George Weale dfb8638eae chore: fix the cleanup_unused_files tool in yaml agent to use the same directory as other tools
PiperOrigin-RevId: 818846060
2025-10-13 15:01:36 -07:00
George Weale 3c0b99a19e fix: rollback of add structured JSON logging with Cloud Trace correlation Close #1683
PiperOrigin-RevId: 818844025
2025-10-13 14:57:23 -07:00
George Weale d8548aabd2 feat: add structured JSON logging with Cloud Trace correlation Close #1683
- 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
2025-10-13 14:08:45 -07:00
Google Team Member df05ed6b3b feat: migrate invocation_context to callback_context
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
2025-10-13 14:05:44 -07:00
Google Team Member 2158b3c915 fix: correctly populate context_id in remote_a2a_agent library when constructing a2a request
PiperOrigin-RevId: 818813897
2025-10-13 13:45:54 -07:00
George Weale e2072af69f feat: migrate invocation_context to callback_context
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
2025-10-13 13:09:15 -07:00
Xiang (Sean) Zhou fa84bcb575 chore: Correct the callback signatures
PiperOrigin-RevId: 818781277
2025-10-13 12:30:37 -07:00
Shangjie Chen bb1ea74924 chore: Delegate the agent state reset logic to LoopAgent
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
2025-10-13 11:53:59 -07:00
Xiang (Sean) Zhou 214986ebeb chore: Adjust the instruction about default model
PiperOrigin-RevId: 818765464
2025-10-13 11:52:11 -07:00
Ankur Sharma 348e552ba6 chore: Remove deprecated run_evals from cli_eval.py
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
2025-10-13 10:13:12 -07:00
Google Team Member e212ff558e feat: Add new methods in the artifact service interface
PiperOrigin-RevId: 818473733
2025-10-12 21:19:20 -07:00
Xuan Yang e63180cb62 feat: Add the support for returning struct_data.uri in DiscoveryEngineSearchTool
For https://github.com/google/adk-python/issues/3146

PiperOrigin-RevId: 818458080
2025-10-12 20:28:08 -07:00
Google Team Member 6da7274858 feat: Set default for bypass_multi_tools_limit to False for GoogleSearchTool and VertexAiSearchTool
PiperOrigin-RevId: 818053371
2025-10-11 09:57:36 -07:00
Xuan Yang b21d0a50d6 fix: Add more clear instruction to the doc updater agent about one PR for each recommended change
PiperOrigin-RevId: 817831087
2025-10-10 16:37:12 -07:00
Joe Fernandez 16b030b2b2 fix: Add a guideline to avoid content deletion
Directs agent to avoid deleting existing content

PiperOrigin-RevId: 817823999
2025-10-10 16:12:16 -07:00
Xinran (Sherry) Tang 59670d240e feat: Support resuming from a paused invocation starting from a sub-agent
PiperOrigin-RevId: 817766247
2025-10-10 13:24:02 -07:00
Google Team Member bddc70b5d0 fix: Better handling the A2A streaming tasks so calling Agent can tell whether it's in progress updates (thought) or the final response
PiperOrigin-RevId: 817682171
2025-10-10 09:46:54 -07:00
George Weale 85ed500871 fix: Add support for file URIs in LiteLLM content conversion to fix issue #3131
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
2025-10-10 08:39:17 -07:00
Ankur Sharma 998264a5b1 fix: Only exclude scores that are None
Scores with values 0 (or 0.0) were also getting excluded.

PiperOrigin-RevId: 817658059
2025-10-10 08:38:18 -07:00
Xuan Yang 9a6b8507f0 feat: Add bypass_multi_tools_limit option to GoogleSearchTool and VertexAiSearchTool
PiperOrigin-RevId: 817493869
2025-10-09 23:05:02 -07:00
Ankur Sharma 64646e0002 chore: Remove deprecated static methods from TrajectoryEvaluator
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
2025-10-09 22:02:24 -07:00
Hangfei Lin 81913c85f4 chore: Update README md with recent ADK features
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
2025-10-09 21:23:37 -07:00
Xiang (Sean) Zhou 9e0b1fb62b fix: Create context cache only when prefix matches with previous request
PiperOrigin-RevId: 817468275
2025-10-09 21:19:28 -07:00
Hangfei Lin 731bb9078d chore: Announce the first ADK Community Call in the README
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
2025-10-09 20:35:47 -07:00
Ankur Sharma ae139bb461 feat: ADK cli allows developers to create an eval set and add an eval case
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
2025-10-09 20:31:01 -07:00
Xinran (Sherry) Tang 9939e0b087 feat: Support resuming a parallel agent with multiple branches paused on tool confirmation requests
PiperOrigin-RevId: 817373403
2025-10-09 16:04:55 -07:00
Xiang (Sean) Zhou cc24d616f8 feat: Support ContentUnion as static instruction
PiperOrigin-RevId: 817278990
2025-10-09 11:52:24 -07:00
Wei Sun (Jack) 0aede9f1a1 docs: Update CHANGELOG with [847df16](https://github.com/google/adk-python/commit/847df1638cbf1686aa43e8e094121d4e23e40245)
PiperOrigin-RevId: 817267158
2025-10-09 11:24:48 -07:00
George Weale 847df1638c fix: handle App instances returned by agent_loader.load_agent
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
2025-10-09 09:00:30 -07:00
Kacper Jawoszek 55aa6f669b feat(otel): set default_log_name for GCP logging exporter
Uses value of GCP_DEFAULT_LOG_NAME env var if it exists, defaults to literal adk-otel.

PiperOrigin-RevId: 817125337
2025-10-09 04:38:26 -07:00
Xuan Yang 9b8a4aad6f chore: Add an sample agent for the ReflectAndRetryToolPlugin
PiperOrigin-RevId: 817024977
2025-10-08 23:05:25 -07:00
Xiang (Sean) Zhou cac9fae829 chore: Don't label 'bot triaged' for PR
PiperOrigin-RevId: 816959715
2025-10-08 19:21:35 -07:00
Wei Sun (Jack) 24342e95f8 chore: Remove temp state deltas before appending an event
PiperOrigin-RevId: 816902208
2025-10-08 16:13:52 -07:00
Ankur Sharma cbe60c47aa feat: Adds data model to support UserSimulation
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
2025-10-08 15:23:57 -07:00
Xiang (Sean) Zhou 2efaa57575 chore: Don't label issue as bot triaged
PiperOrigin-RevId: 816873967
2025-10-08 14:58:49 -07:00
Xinran (Sherry) Tang 32f2ec3a78 feat: Set agent_state in invocation context right before yielding the checkpoint event
PiperOrigin-RevId: 816804179
2025-10-08 12:01:57 -07:00
Shangjie Chen 75179243b4 chore: Update human_tool_confirmation agent to use resumability feature
PiperOrigin-RevId: 816793131
2025-10-08 11:35:13 -07:00
Wei Sun (Jack) 03f051d3ed chore: Bumps version to v1.16.0 and updates CHANGELOG
PiperOrigin-RevId: 816788551
2025-10-08 11:26:58 -07:00
George Weale e858dc0799 chore: change how agent builder assistant instructions for model selection asking, to make it ask once for plan and one for model selection
PiperOrigin-RevId: 816788530
2025-10-08 11:22:54 -07:00
Google Team Member 0e3c0f78f5 feat: Make session_id optional in BaseArtifactService methods
PiperOrigin-RevId: 816782982
2025-10-08 11:08:41 -07:00
Xiang (Sean) Zhou f2bed14c4b chore: Adjust the LLM Request logging
1. function declarations is not necessary in the first tool
2. log the config

PiperOrigin-RevId: 816547534
2025-10-07 23:07:18 -07:00
Haoming Chen 30212669ff docs: Update BigQuery samples README
Add the new analyze_contribution tool and renumbering as the Github cannot display it correctly.

PiperOrigin-RevId: 816517893
2025-10-07 21:19:40 -07:00
Hangfei Lin 3f2b457efd fix: fix compaction logic
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
2025-10-07 21:16:07 -07:00
Che Liu e55b8946d6 feat: Add ReflectRetryToolPlugin to reflect from errors and retry with different arguments when tool errors
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
2025-10-07 17:56:54 -07:00
Douglas Reid 2b5acb98f5 feat(models): add support for gemma model via gemini api
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
2025-10-07 17:38:35 -07:00
Hangfei Lin 84f2f417f7 fix: Rollback compaction handling from _get_contents
The sorting may cause problems in complex cases so rolling it back. Will implement it with a non-sorting approach.

PiperOrigin-RevId: 816420710
2025-10-07 16:11:36 -07:00
Google Team Member 8110e41b36 fix: VertexSessionService with adding base_url override to base api override without removing initialized http_options
PiperOrigin-RevId: 816409410
2025-10-07 15:43:17 -07:00
Xuan Yang b0f0698ec2 chore: Add a sample agent to demonstrate that built-in google search tool and VertexAiSearchTool can be used together with other tools
PiperOrigin-RevId: 816396360
2025-10-07 15:08:53 -07:00
Xinran (Sherry) Tang db41f54e7b chore: When processing pending tool confirmation requests, only look at events in the same branch
PiperOrigin-RevId: 816387687
2025-10-07 14:48:19 -07:00
Shangjie Chen 636def3687 fix: Add AuthConfig json serialization in vertex ai session service
Resolves https://github.com/google/adk-python/issues/2035

PiperOrigin-RevId: 816387628
2025-10-07 14:47:28 -07:00
Xiang (Sean) Zhou 3f86760e0b chore: Remove unnecessary check tool type and tool attribute
tool in config.tools cann't be ToolDict and must have computer_use attr

PiperOrigin-RevId: 816368064
2025-10-07 14:01:53 -07:00
Yifan Wang 5ac446d947 chore: add invocation_id to AgentRunRequest for resuming long running functions
PiperOrigin-RevId: 816362937
2025-10-07 13:49:50 -07:00
Xuan Yang 2699ad7aff chore: fix the test_llm_agent_fields.py by adding a mock for google.auth.default
PiperOrigin-RevId: 816319357
2025-10-07 12:05:48 -07:00
Xuan Yang 4485379a04 ADK changes
PiperOrigin-RevId: 816288113
2025-10-07 10:59:19 -07:00
Xiang (Sean) Zhou 0989d64688 chore: Remove unnecessary check tool type and tool attribute
tool in config.tools cann't be ToolDict and must have computer_use attr

PiperOrigin-RevId: 816283438
2025-10-07 10:48:48 -07:00
Shangjie Chen 90d4c19c51 feat: Migrate vertex ai session service to use agent engine sdk
PiperOrigin-RevId: 816259798
2025-10-07 09:58:27 -07:00
Xiang (Sean) Zhou 3be9cd844c chore: Let tools to handle root directory resolvement and model only knows the project name and always use relative path
PiperOrigin-RevId: 816213558
2025-10-07 08:11:06 -07:00
Hangfei Lin 3f4bd67b49 fix: Make compactor optional in EventsCompactionConfig and add a default
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
2025-10-06 22:20:49 -07:00
Bo Yang 238472d083 fix: Updates the load_artifacts tool so that the model can reliability call it for follow up questions about the same artifact
PiperOrigin-RevId: 816025399
2025-10-06 21:34:51 -07:00
Hangfei Lin f1abdb1938 fix: Rename SlidingWindowCompactor to LlmEventSummarizer and refine its docstring
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
2025-10-06 18:54:20 -07:00
Hangfei Lin 68402bda49 fix: Set default response modality to AUDIO in run_session
Some native audio models require the modality to be set, so we default to AUDIO if not specified in `RunConfig`.

PiperOrigin-RevId: 815952039
2025-10-06 17:37:10 -07:00
Xiang (Sean) Zhou 90e1e3e10c chore: Add sample agent for testing oatuh2 client credentials grant type
PiperOrigin-RevId: 815863131
2025-10-06 13:34:09 -07:00
Haoming Chen 4bb089d386 feat: Add BigQuery analyze_contribution tool
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
2025-10-06 12:59:09 -07:00
Xiang (Sean) Zhou 5c6cdcd197 feat: Support Oauth2 client credentials grant type
PiperOrigin-RevId: 815813477
2025-10-06 11:28:17 -07:00
George Weale 46d73be41a chore: Add more info to "Session not found" error message in ADK runners for differently named app and folder
PiperOrigin-RevId: 815795412
2025-10-06 10:48:28 -07:00
Hangfei Lin e0dd06ff04 feat: implementation of LLM context compaction
Provide a more efficient way to compact LLM context for better agentic performance.

PiperOrigin-RevId: 815785898
2025-10-06 10:28:46 -07:00
Xiang (Sean) Zhou ca6a4340f4 chore: Move adk knowledge agent out of adk agent builder folder
PiperOrigin-RevId: 815771308
2025-10-06 09:57:21 -07:00
George Weale 86de3ef7e3 chore: google.genai instead of `google.generativeai'
PiperOrigin-RevId: 815759570
2025-10-06 09:27:13 -07:00
Max Ind bd76b46ce2 feat(otel): Switch CloudTraceSpanExporter to telemetry.googleapis.com
PiperOrigin-RevId: 815675872
2025-10-06 05:14:32 -07:00
Xiang (Sean) Zhou 4b47a0a552 chore: Add instructions for callback signatures
PiperOrigin-RevId: 815549924
2025-10-05 21:47:53 -07:00
Xuan Yang 84c1faeeef chore: Introduce the remote A2A ADK Knowledge Agent to Agent Builder Assistant
PiperOrigin-RevId: 815543707
2025-10-05 21:21:19 -07:00
Xiang (Sean) Zhou c6dd444fc9 fix: Adapt to new computer use tool name in genai sdk 1.41.0
1.40.0 has some bug that caused some UT tests failures

PiperOrigin-RevId: 815098429
2025-10-04 08:53:13 -07:00
Google Team Member d1efc8461e feat: Migrate vertex_ai_session_service to use Agent Engine SDK
PiperOrigin-RevId: 814967790
2025-10-03 22:14:23 -07:00
Shangjie Chen 97b950b36b feat: Migrate vertex_ai_session_service to use Agent Engine SDK
PiperOrigin-RevId: 814948921
2025-10-03 21:00:15 -07:00
Google Team Member 960eda3d1f feat: Add dry_run functionality to BigQuery execute_sql tool
PiperOrigin-RevId: 814854520
2025-10-03 15:36:58 -07:00
Xiang (Sean) Zhou 0b84d3eea7 chore: Show relative path in response if root directory already set in session state
PiperOrigin-RevId: 814768273
2025-10-03 11:33:24 -07:00
Xiang (Sean) Zhou 611b604bdc chore: Emphasize not to ask for root_directory if it's set in the context
PiperOrigin-RevId: 814738676
2025-10-03 10:14:44 -07:00
Xiang (Sean) Zhou 33b2d495be chore: Emphasize "model" property can inherit from parent LlmAgent
PiperOrigin-RevId: 814715394
2025-10-03 09:06:33 -07:00
Max Ind 0162898707 ADK changes
PiperOrigin-RevId: 814614027
2025-10-03 02:56:51 -07:00
Xuan Yang 42db35111b chore: fix typo for GenerateContentConfig in Agent Builder Assistant
PiperOrigin-RevId: 814495803
2025-10-02 19:56:55 -07:00
George Weale dd0571ad09 chore: Clarify write_config_files usage for sub-agent YAML files
PiperOrigin-RevId: 814489632
2025-10-02 19:36:15 -07:00
George Weale a4ef7edcbb chore: add __init__.py prompt for tool imports
PiperOrigin-RevId: 814488943
2025-10-02 19:33:58 -07:00
Xiang (Sean) Zhou c5b976b306 chore: Create the context cache based on the token count of previous request
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
2025-10-02 19:22:00 -07:00
Xuan Yang 420df25f58 chore: add a remote A2A knowledge agent for Agent Builder Assistant
PiperOrigin-RevId: 814484204
2025-10-02 19:20:36 -07:00
Google Team Member a9b76b9061 ADK changes
PiperOrigin-RevId: 814417092
2025-10-02 15:49:48 -07:00
Google Team Member 65d6da081c ADK changes
PiperOrigin-RevId: 814413627
2025-10-02 15:49:35 -07:00
Shangjie Chen b170a84279 chore: Handle exception in preload_memory_tool to not fail the llm request
Resolves https://github.com/google/adk-python/issues/3069

PiperOrigin-RevId: 814391260
2025-10-02 14:41:27 -07:00
Wei Sun (Jack) 5b8d523a4b ADK changes
PiperOrigin-RevId: 814367778
2025-10-02 13:44:16 -07:00
Xuan Yang d3148dacc9 ADK changes
PiperOrigin-RevId: 814319961
2025-10-02 13:44:05 -07:00
George Weale 2e2d61b6fe fix: Set max_output_tokens for the agent builder
PiperOrigin-RevId: 814317909
2025-10-02 13:43:55 -07:00
Ankur Sharma 65554d6621 chore: Update AgentEvaluator to use EvalConfig
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
2025-10-02 13:43:44 -07:00
George Weale e68006386f fix: Fixes a bug that causes intermittent pydantic validation errors when uploading files
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
2025-10-02 13:43:34 -07:00
George Weale f667c7445e chore: deprecate global_instructions and make it a plugin instead
PiperOrigin-RevId: 814307563
2025-10-02 13:43:22 -07:00
Xiang (Sean) Zhou 29f18f4eea chore: Add a sample agent to test pydantic models as function tool argument
PiperOrigin-RevId: 814293450
2025-10-02 13:43:10 -07:00
Xiang (Sean) Zhou 571c802fba fix: Convert argument to pydantic model when tool declare to accept pydantic model as argument
PiperOrigin-RevId: 814273005
2025-10-02 13:43:00 -07:00
Xiang (Sean) Zhou c46308b7cf chore: Add session patch endpoint to api server for state update
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
2025-10-02 13:42:49 -07:00
Hoonji Baek 822efe0065 feat: Adds adk web options for custom logo
Allows users to configure a custom text and logo for their ADK Web app using `--logo-text` and `--logo-image-url` flags.

PiperOrigin-RevId: 814016542
2025-10-02 13:42:38 -07:00
Shangjie Chen 55bc985821 chore: Fix vertexai import rule of memory service for google internal dependencies
PiperOrigin-RevId: 813941520
2025-10-02 13:42:23 -07:00
Google Team Member da62700d73 feat: Spanner ADK toolset supports customizable template SQL and parameterized SQL
PiperOrigin-RevId: 813909122
2025-10-01 14:15:01 -07:00
Google Team Member a5cf80b952 fix: Handling of A2ATaskStatusUpdateEvent when streaming in remote_a2a_agent
The proto has the Message object in the TaskStatus.

PiperOrigin-RevId: 813844289
2025-10-01 11:43:03 -07:00
Xuan Yang 29968d44ae chore: Remove get_working_directory_info from instruction template for agent builder assistant
PiperOrigin-RevId: 813495752
2025-09-30 17:29:33 -07:00
Yifan Wang ce2167861c chore: Adding builder endpoints, WIP
PiperOrigin-RevId: 813489379
2025-09-30 17:10:38 -07:00
Joseph Pagadora 8c73d29c75 feat: Add HallucinationsV1 evaluation metric
PiperOrigin-RevId: 813456369
2025-09-30 15:39:10 -07:00
Xuan Yang a239716930 ADK changes
PiperOrigin-RevId: 813321782
2025-09-30 10:18:30 -07:00
Google Team Member c51ea0b52e fix: VertexSessionService with adding base_url override to base api override without removing initialized http_options
PiperOrigin-RevId: 813319796
2025-09-30 10:14:58 -07:00
Liang Wu 8f3ca0359e fix: fix the instruction in workflow_triage example agent
PiperOrigin-RevId: 813305068
2025-09-30 09:37:54 -07:00
Joe Fernandez 745996212d fix: Added more agent instructions for doc content changes
Add directives for content updates and writing style

PiperOrigin-RevId: 813284600
2025-09-30 08:44:59 -07:00
Shangjie Chen 83fd045718 feat: Migrate VertexAiMemoryBankService to use Agent Engine SDK
PiperOrigin-RevId: 813104746
2025-09-29 23:14:50 -07:00
Shangjie Chen ce9c39f5a8 feat: Implement checkpoint and resume logic for LoopAgent
PiperOrigin-RevId: 813096880
2025-09-29 22:45:57 -07:00
Wei Sun (Jack) d5c46e4960 fix: Do not re-create App object when loader returns an App
PiperOrigin-RevId: 813083541
2025-09-29 22:02:19 -07:00
Xinran (Sherry) Tang fbf75761bb feat: Modify runner to support resuming an invocation (optionally with a function response)
PiperOrigin-RevId: 813008406
2025-09-29 17:35:18 -07:00
Xinran (Sherry) Tang f005414895 feat: Make resumable llm agents yield checkpoint events
PiperOrigin-RevId: 813001108
2025-09-29 17:08:58 -07:00
Ankur Sharma 609a2358eb chore: PrettyPrint the output of detailed results generated from adk eval cli command
PiperOrigin-RevId: 812912413
2025-09-29 13:09:31 -07:00
Xinran (Sherry) Tang 772658fd81 chore: Refactor runner run_async flow to extract out execution context setup logic
PiperOrigin-RevId: 812894540
2025-09-29 12:21:45 -07:00
Google Team Member 8e5f361264 fix: Update remote_a2a_agent to better handle streaming events and avoid duplicate responses
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
2025-09-29 11:42:49 -07:00
Google Team Member b1ee013347 chore: Remove debug print from get_agent_graph
PiperOrigin-RevId: 812767234
2025-09-29 06:48:06 -07:00
Shangjie Chen 2f1040f296 feat: Implement checkpoint and resume logic for ParallelAgent
PiperOrigin-RevId: 812658378
2025-09-29 00:26:32 -07:00
Xiang (Sean) Zhou 943abec7c0 chore: Clarify the rule for getting tool name prefix in instruction
PiperOrigin-RevId: 812097390
2025-09-26 23:10:24 -07:00
Google Team Member 3f28e30c6d feat: add citation_metadata to LlmResponse
PiperOrigin-RevId: 811997009
2025-09-26 16:31:01 -07:00
Shangjie Chen 7b707cebea chore: Simplfiy the parallel agent py version handling logic
PiperOrigin-RevId: 811992425
2025-09-26 16:15:51 -07:00
Ankur Sharma c984b9e552 feat: Add Rubric based tool use metric
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
2025-09-26 15:47:42 -07:00
Xuan Yang a959653cf3 chore: bump version to 1.15.1 with a patch for Agent Engine
PiperOrigin-RevId: 811981894
2025-09-26 15:42:12 -07:00
Shangjie Chen 1ee01cc05a feat: Implement checkpoint and resume logic for SequentialAgent
PiperOrigin-RevId: 811977004
2025-09-26 15:26:42 -07:00
Xinran (Sherry) Tang 28d44a365a test: Make testing_utils.InMemoryRunner support ADK App and add utils for extracting event contents for testing resumability
PiperOrigin-RevId: 811933527
2025-09-26 13:22:11 -07:00
Sasha Sobran e172811bc7 fix: unbreak client closed errors when using vertexai session service
PiperOrigin-RevId: 811911528
2025-09-26 12:16:37 -07:00
Xuan Yang da6f1d3653 chore: Release ADK 1.15.0
PiperOrigin-RevId: 811655912
2025-09-25 22:17:23 -07:00
Shangjie Chen 2c752934a8 feat: Skip running a workflow agent if it has no sub-agents
PiperOrigin-RevId: 811528166
2025-09-25 15:39:38 -07:00
Xinran (Sherry) Tang b2b80e7fa0 feat: Pause invocations on long running function calls for resumable apps
PiperOrigin-RevId: 811518771
2025-09-25 15:11:11 -07:00
Xuan Yang dd1ffad394 chore: Update google-genai version constraint
Fixes https://github.com/google/adk-python/issues/2968

PiperOrigin-RevId: 811475972
2025-09-25 13:21:45 -07:00
Shangjie Chen 8b081751ed feat: Add core checkpointing primitive for base agent
PiperOrigin-RevId: 811458903
2025-09-25 12:35:36 -07:00
Xinran (Sherry) Tang b5a65fb4f4 chore: Remove the too-detailed edge case descriptions for resumability
PiperOrigin-RevId: 811432962
2025-09-25 11:32:38 -07:00
Shangjie Chen 839d2e43bb feat: Define an AgentState to be used for resuming agent invocation
PiperOrigin-RevId: 811414736
2025-09-25 10:49:49 -07:00
Xiang (Sean) Zhou 1589fcdd86 chore: Replace github HTTP URIs with GCS HTTP URIs in static non-text content sample agent
mainly because http://github.com/robots.txt disallows `/*/raw/` path. using GCS HTTP URIs is more reliable with Gemini model.

PiperOrigin-RevId: 811409688
2025-09-25 10:38:04 -07:00
Max Ind e7528aebd4 feat(otel): adjust telemetry to follow OTLP 1.37 GenAI semconv
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
2025-09-25 09:25:15 -07:00
Xinran (Sherry) Tang cbb6e4945a feat: Add a app level config for resumable applications
PiperOrigin-RevId: 811272046
2025-09-25 03:14:34 -07:00
Xiang (Sean) Zhou c6b6b6f3c6 chore: Add log-level parameter to cache analysis experiments
this is to allow turning on debug log for debugging if some unexpected behavior observed during running cache analysis experiments.

PiperOrigin-RevId: 811189954
2025-09-24 22:44:41 -07:00
Google Team Member c8c6cd70a4 feat: Introduce ExtendedOAuth2 scheme that auto-populates auth/token URLs
Use auto-discovered auth_endpoint and token_endpoint in CredentialManager.

PiperOrigin-RevId: 811183929
2025-09-24 22:21:07 -07:00
1367 changed files with 149041 additions and 18296 deletions
+3
View File
@@ -0,0 +1,3 @@
{
".": "1.26.0"
}
+52 -17
View File
@@ -7,34 +7,69 @@ assignees: ''
---
** Please make sure you read the contribution guide and file the issues in the right place. **
[Contribution guide.](https://google.github.io/adk-docs/contributing-guide/)
## 🔴 Required Information
*Please ensure all items in this section are completed to allow for efficient
triaging. Requests without complete information may be rejected / deprioritized.
If an item is not applicable to you - please mark it as N/A*
**Describe the bug**
**Describe the Bug:**
A clear and concise description of what the bug is.
**To Reproduce**
Please share a minimal code and data to reproduce your problem.
Steps to reproduce the behavior:
**Steps to Reproduce:**
Please provide a numbered list of steps to reproduce the behavior:
1. Install '...'
2. Run '....'
3. Open '....'
4. Provie error or stacktrace
4. Provide error or stacktrace
**Expected behavior**
**Expected Behavior:**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Observed Behavior:**
What actually happened? Include error messages or crash stack traces here.
**Desktop (please complete the following information):**
- OS: [e.g. macOS, Linux, Windows]
- Python version(python -V):
- ADK version(pip show google-adk):
**Environment Details:**
- ADK Library Version (pip show google-adk):
- Desktop OS:** [e.g., macOS, Linux, Windows]
- Python Version (python -V):
**Model Information:**
**Model Information:**
- Are you using LiteLLM: Yes/No
- Which model is being used(e.g. gemini-2.5-pro)
- Which model is being used: (e.g., gemini-2.5-pro)
**Additional context**
---
## 🟡 Optional Information
*Providing this information greatly speeds up the resolution process.*
**Regression:**
Did this work in a previous version of ADK? If so, which one?
**Logs:**
Please attach relevant logs. Wrap them in code blocks (```) or attach a
text file.
```text
// Paste logs here
```
**Screenshots / Video:**
If applicable, add screenshots or screen recordings to help explain
your problem.
**Additional Context:**
Add any other context about the problem here.
**Minimal Reproduction Code:**
Please provide a code snippet or a link to a Gist/repo that isolates the issue.
```python
// Code snippet here
```
**How often has this issue occurred?:**
- Always (100%)
- Often (50%+)
- Intermittently (<50%)
- Once / Rare
+33 -8
View File
@@ -10,14 +10,39 @@ assignees: ''
** Please make sure you read the contribution guide and file the issues in the right place. **
[Contribution guide.](https://google.github.io/adk-docs/contributing-guide/)
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
## 🔴 Required Information
*Please ensure all items in this section are completed to allow for efficient
triaging. Requests without complete information may be rejected / deprioritized.
If an item is not applicable to you - please mark it as N/A*
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
### Is your feature request related to a specific problem?
Please describe the problem you are trying to solve. (Ex: "I'm always frustrated
when I have to manually handle X...")
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
### Describe the Solution You'd Like
A clear and concise description of the feature or API change you want.
Be specific about input/outputs if this involves an API change.
**Additional context**
Add any other context or screenshots about the feature request here.
### Impact on your work
How does this feature impact your work and what are you trying to achieve?
If this is critical for you, tell us if there is a timeline by when you need
this feature.
### Willingness to contribute
Are you interested in implementing this feature yourself or submitting a PR?
(Yes/No)
---
## 🟡 Recommended Information
### Describe Alternatives You've Considered
A clear and concise description of any alternative solutions or workarounds
you've considered and why they didn't work for you.
### Proposed API / Implementation
If you have ideas on how this should look in code, please share a
pseudo-code example.
### Additional Context
Add any other context or screenshots about the feature request here.
+52
View File
@@ -0,0 +1,52 @@
**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._
+61
View File
@@ -0,0 +1,61 @@
{
"$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json",
"last-release-sha": "8f5428150d18ed732b66379c0acb806a9121c3cb",
"packages": {
".": {
"release-type": "python",
"versioning": "always-bump-minor",
"package-name": "google-adk",
"include-component-in-tag": false,
"skip-github-release": true,
"changelog-path": "CHANGELOG.md",
"changelog-sections": [
{
"type": "feat",
"section": "Features"
},
{
"type": "fix",
"section": "Bug Fixes"
},
{
"type": "perf",
"section": "Performance Improvements"
},
{
"type": "refactor",
"section": "Code Refactoring"
},
{
"type": "docs",
"section": "Documentation"
},
{
"type": "test",
"section": "Tests",
"hidden": true
},
{
"type": "build",
"section": "Build System",
"hidden": true
},
{
"type": "ci",
"section": "CI/CD",
"hidden": true
},
{
"type": "style",
"section": "Styles",
"hidden": true
},
{
"type": "chore",
"section": "Miscellaneous Chores",
"hidden": true
}
]
}
}
}
-5
View File
@@ -1,5 +0,0 @@
releaseType: python
handleGHRelease: true
bumpMinorPreMajor: false
extraFiles:
- src/google/adk/version.py
-1
View File
@@ -1 +0,0 @@
enabled: true
@@ -16,15 +16,15 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v6
with:
python-version: '3.11'
- name: Load adk-bot SSH Private Key
uses: webfactory/ssh-agent@v0.9.0
uses: webfactory/ssh-agent@v0.9.1
with:
ssh-private-key: ${{ secrets.ADK_BOT_SSH_PRIVATE_KEY }}
+10 -10
View File
@@ -1,4 +1,4 @@
# Copyright 2025 Google LLC
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -24,14 +24,14 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 2
- name: Check for logger pattern in all changed Python files
run: |
git fetch origin ${{ github.base_ref }}
CHANGED_FILES=$(git diff --diff-filter=ACMR --name-only origin/${{ github.base_ref }}...HEAD | grep -E '\.py$' || true)
git fetch origin ${GITHUB_BASE_REF}
CHANGED_FILES=$(git diff --diff-filter=ACMR --name-only origin/${GITHUB_BASE_REF}...HEAD | grep -E '\.py$' || true)
if [ -n "$CHANGED_FILES" ]; then
echo "Changed Python files to check:"
echo "$CHANGED_FILES"
@@ -61,8 +61,8 @@ jobs:
- name: Check for import pattern in certain changed Python files
run: |
git fetch origin ${{ github.base_ref }}
CHANGED_FILES=$(git diff --diff-filter=ACMR --name-only origin/${{ github.base_ref }}...HEAD | grep -E '\.py$' | grep -v -E '__init__.py$|version.py$|tests/.*|contributing/samples/' || true)
git fetch origin ${GITHUB_BASE_REF}
CHANGED_FILES=$(git diff --diff-filter=ACMR --name-only origin/${GITHUB_BASE_REF}...HEAD | grep -E '\.py$' | grep -v -E '__init__.py$|version.py$|tests/.*|contributing/samples/' || true)
if [ -n "$CHANGED_FILES" ]; then
echo "Changed Python files to check:"
echo "$CHANGED_FILES"
@@ -88,15 +88,15 @@ jobs:
- name: Check for import from cli package in certain changed Python files
run: |
git fetch origin ${{ github.base_ref }}
CHANGED_FILES=$(git diff --diff-filter=ACMR --name-only origin/${{ github.base_ref }}...HEAD | grep -E '\.py$' | grep -v -E 'cli/.*|tests/.*|contributing/samples/' || true)
git fetch origin ${GITHUB_BASE_REF}
CHANGED_FILES=$(git diff --diff-filter=ACMR --name-only origin/${GITHUB_BASE_REF}...HEAD | grep -E '\.py$' | grep -v -E 'cli/.*|src/google/adk/tools/apihub_tool/apihub_toolset.py|tests/.*|contributing/samples/' || true)
if [ -n "$CHANGED_FILES" ]; then
echo "Changed Python files to check:"
echo "$CHANGED_FILES"
echo ""
set +e
FILES_WITH_FORBIDDEN_IMPORT=$(grep -lE '^from.*cli.*import.*$' $CHANGED_FILES)
FILES_WITH_FORBIDDEN_IMPORT=$(grep -lE '^from.*\bcli\b.*import.*$' $CHANGED_FILES)
GREP_EXIT_CODE=$?
set -e
@@ -110,4 +110,4 @@ jobs:
fi
else
echo "✅ No relevant Python files found."
fi
fi
+134
View File
@@ -0,0 +1,134 @@
name: Copybara PR Handler
on:
push:
branches:
- main
workflow_dispatch:
inputs:
pr_number:
description: 'PR number to close (for testing)'
required: true
type: string
commit_sha:
description: 'Commit SHA reference (optional, for testing)'
required: false
type: string
jobs:
close-imported-pr:
runs-on: ubuntu-latest
permissions:
pull-requests: write
issues: write
contents: read
steps:
- name: Check for Copybara commits and close PRs
uses: actions/github-script@v8
with:
github-token: ${{ secrets.ADK_TRIAGE_AGENT }}
script: |
// Check if this is a manual test run
const isManualRun = context.eventName === 'workflow_dispatch';
let prsToClose = [];
if (isManualRun) {
// Manual testing mode
const prNumber = parseInt(context.payload.inputs.pr_number);
const commitSha = context.payload.inputs.commit_sha || context.sha.substring(0, 7);
console.log('=== MANUAL TEST MODE ===');
console.log(`Testing with PR #${prNumber}, commit ${commitSha}`);
prsToClose.push({ prNumber, commitSha });
} else {
// Normal mode: process commits from push event
const commits = context.payload.commits || [];
console.log(`Found ${commits.length} commit(s) in this push`);
// Process each commit
for (const commit of commits) {
const sha = commit.id;
const committer = commit.committer.name;
const message = commit.message;
console.log(`\n--- Processing commit ${sha.substring(0, 7)} ---`);
console.log(`Committer: ${committer}`);
// Check if this is a Copybara commit
if (committer !== 'Copybara-Service') {
console.log('Not a Copybara commit, skipping');
continue;
}
// Extract PR number from commit message
// Pattern: "Merge https://github.com/google/adk-python/pull/3333"
const prMatch = message.match(/Merge https:\/\/github\.com\/google\/adk-python\/pull\/(\d+)/);
if (!prMatch) {
console.log('No PR number found in Copybara commit message');
continue;
}
const prNumber = parseInt(prMatch[1]);
const commitSha = sha.substring(0, 7);
prsToClose.push({ prNumber, commitSha });
}
}
// Process PRs to close
for (const { prNumber, commitSha } of prsToClose) {
console.log(`\n--- Processing PR #${prNumber} ---`);
// Get PR details to check if it's open
let pr;
try {
pr = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: prNumber
});
} catch (error) {
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.`
});
// Close the PR
await github.rest.pulls.update({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: prNumber,
state: 'closed'
});
console.log(`Successfully closed PR #${prNumber}`);
} catch (error) {
console.log(`Error closing PR #${prNumber}:`, error.message);
}
}
if (isManualRun) {
console.log('\n=== TEST COMPLETED ===');
} else {
console.log('\n--- Finished processing all commits ---');
}
+3 -3
View File
@@ -15,16 +15,16 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v6
with:
python-version: '3.11'
- name: Authenticate to Google Cloud
id: auth
uses: 'google-github-actions/auth@v2'
uses: 'google-github-actions/auth@v3'
with:
credentials_json: '${{ secrets.ADK_GCP_SA_KEY }}'
+6 -6
View File
@@ -1,4 +1,4 @@
# Copyright 2025 Google LLC
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -26,14 +26,14 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 2
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v6
with:
python-version: '3.x'
python-version: '3.11'
- name: Install isort
run: |
@@ -42,8 +42,8 @@ jobs:
- name: Run isort on changed files
id: run_isort
run: |
git fetch origin ${{ github.base_ref }}
CHANGED_FILES=$(git diff --diff-filter=ACMR --name-only origin/${{ github.base_ref }}...HEAD | grep -E '\.py$' || true)
git fetch origin ${GITHUB_BASE_REF}
CHANGED_FILES=$(git diff --diff-filter=ACMR --name-only origin/${GITHUB_BASE_REF}...HEAD | grep -E '\.py$' || true)
if [ -n "$CHANGED_FILES" ]; then
echo "Changed Python files:"
echo "$CHANGED_FILES"
+74
View File
@@ -0,0 +1,74 @@
name: Mypy New Error Check
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
mypy-diff:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.10', '3.11', '3.12', '3.13',]
steps:
- name: Checkout code
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Generate Baseline (Main)
run: |
# Switch to main branch to generate baseline
git checkout origin/main
git checkout ${{ github.sha }} -- pyproject.toml
# Install dependencies for main
uv venv .venv
source .venv/bin/activate
uv sync --all-extras
# Run mypy, filter for errors only, remove line numbers (file:123: -> file::), and sort
# We ignore exit code (|| true) because we expect errors on main
uv run mypy . | grep "error:" | sed 's/:\([0-9]\+\):/::/g' | sort > main_errors.txt || true
echo "Found $(wc -l < main_errors.txt) errors on main."
- name: Check PR Branch
run: |
# Switch back to the PR commit
git checkout ${{ github.sha }}
# Re-sync dependencies in case the PR changed them
source .venv/bin/activate
uv sync --all-extras
# Run mypy on PR code, apply same processing
uv run mypy . | grep "error:" | sed 's/:\([0-9]\+\):/::/g' | sort > pr_errors.txt || true
echo "Found $(wc -l < pr_errors.txt) errors on PR branch."
- name: Compare and Fail on New Errors
run: |
# 'comm -13' suppresses unique lines in file1 (main) and common lines,
# leaving only lines unique to file2 (PR) -> The new errors.
comm -13 main_errors.txt pr_errors.txt > new_errors.txt
if [ -s new_errors.txt ]; then
echo "::error::The following NEW mypy errors were introduced:"
cat new_errors.txt
exit 1
else
echo "Great job! No new mypy errors introduced."
fi
+29
View File
@@ -0,0 +1,29 @@
name: Mypy Type Check
on:
workflow_dispatch:
jobs:
mypy:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.10', '3.11', '3.12', '3.13',]
steps:
- uses: actions/checkout@v6
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: uv sync --all-extras
- name: Run mypy
run: uv run mypy . --strict
+10 -4
View File
@@ -3,10 +3,16 @@ name: ADK Pull Request Triaging Agent
on:
pull_request_target:
types: [opened, reopened, edited]
workflow_dispatch:
inputs:
pr_number:
description: 'The Pull Request number to triage'
required: true
type: 'string'
jobs:
agent-triage-pull-request:
if: "!contains(github.event.pull_request.labels.*.name, 'bot triaged') && !contains(github.event.pull_request.labels.*.name, 'google-contributor')"
if: github.event_name == 'workflow_dispatch' || !contains(github.event.pull_request.labels.*.name, 'google-contributor')
runs-on: ubuntu-latest
permissions:
pull-requests: write
@@ -14,10 +20,10 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v6
with:
python-version: '3.11'
@@ -33,7 +39,7 @@ jobs:
GOOGLE_GENAI_USE_VERTEXAI: 0
OWNER: 'google'
REPO: 'adk-python'
PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }}
PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number || github.event.inputs.pr_number }}
INTERACTIVE: ${{ vars.PR_TRIAGE_INTERACTIVE }}
PYTHONPATH: contributing/samples
run: python -m adk_pr_triaging_agent.main
+6 -6
View File
@@ -1,4 +1,4 @@
# Copyright 2025 Google LLC
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -26,14 +26,14 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 2
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v6
with:
python-version: '3.x'
python-version: '3.11'
- name: Install pyink
run: |
@@ -42,8 +42,8 @@ jobs:
- name: Run pyink on changed files
id: run_pyink
run: |
git fetch origin ${{ github.base_ref }}
CHANGED_FILES=$(git diff --diff-filter=ACMR --name-only origin/${{ github.base_ref }}...HEAD | grep -E '\.py$' || true)
git fetch origin ${GITHUB_BASE_REF}
CHANGED_FILES=$(git diff --diff-filter=ACMR --name-only origin/${GITHUB_BASE_REF}...HEAD | grep -E '\.py$' || true)
if [ -n "$CHANGED_FILES" ]; then
echo "Changed Python files:"
echo "$CHANGED_FILES"
+9 -17
View File
@@ -1,4 +1,4 @@
# Copyright 2025 Google LLC
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -25,37 +25,29 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- name: Install the latest version of uv
uses: astral-sh/setup-uv@v6
uses: astral-sh/setup-uv@v7
- name: Install dependencies
run: |
uv venv .venv
source .venv/bin/activate
uv sync --extra test --extra eval --extra a2a
uv sync --extra test
- name: Run unit tests with pytest
run: |
source .venv/bin/activate
if [[ "${{ matrix.python-version }}" == "3.9" ]]; then
pytest tests/unittests \
--ignore=tests/unittests/a2a \
--ignore=tests/unittests/tools/mcp_tool \
--ignore=tests/unittests/artifacts/test_artifact_service.py \
--ignore=tests/unittests/tools/google_api_tool/test_googleapi_to_openapi_converter.py
else
pytest tests/unittests \
--ignore=tests/unittests/artifacts/test_artifact_service.py \
--ignore=tests/unittests/tools/google_api_tool/test_googleapi_to_openapi_converter.py
fi
pytest tests/unittests \
--ignore=tests/unittests/artifacts/test_artifact_service.py \
--ignore=tests/unittests/tools/google_api_tool/test_googleapi_to_openapi_converter.py
+43
View File
@@ -0,0 +1,43 @@
# Step 3 (optional): Cherry-picks a commit from main to the release/candidate branch.
# Use between step 1 and step 4 to include bug fixes in an in-progress release.
# Note: Does NOT auto-trigger release-please to preserve manual changelog edits.
name: "Release: Cherry-pick"
on:
workflow_dispatch:
inputs:
commit_sha:
description: 'Commit SHA to cherry-pick'
required: true
type: string
permissions:
contents: write
jobs:
cherry-pick:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: release/candidate
fetch-depth: 0
- name: Configure git
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
- name: Cherry-pick commit
run: |
echo "Cherry-picking ${INPUTS_COMMIT_SHA} to release/candidate"
git cherry-pick ${INPUTS_COMMIT_SHA}
env:
INPUTS_COMMIT_SHA: ${{ inputs.commit_sha }}
- name: Push changes
run: |
git push origin release/candidate
echo "Successfully cherry-picked commit to release/candidate"
echo "Note: Release Please is NOT auto-triggered to preserve manual changelog edits."
echo "Run release-please.yml manually if you want to regenerate the changelog."
+46
View File
@@ -0,0 +1,46 @@
# Step 1: Starts the release process by creating a release/candidate branch.
# Generates a changelog PR for review (step 2).
name: "Release: Cut"
on:
workflow_dispatch:
inputs:
commit_sha:
description: 'Commit SHA to cut from (leave empty for latest main)'
required: false
type: string
permissions:
contents: write
actions: write
jobs:
cut-release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit_sha || 'main' }}
- name: Check for existing release/candidate branch
env:
GH_TOKEN: ${{ github.token }}
run: |
if git ls-remote --exit-code --heads origin release/candidate &>/dev/null; then
echo "Error: release/candidate branch already exists"
echo "Please finalize or delete the existing release candidate before starting a new one"
exit 1
fi
- name: Create and push release/candidate branch
run: |
git checkout -b release/candidate
git push origin release/candidate
echo "Created branch: release/candidate"
- name: Trigger Release Please
env:
GH_TOKEN: ${{ github.token }}
run: |
gh workflow run release-please.yml --repo ${{ github.repository }} --ref release/candidate
echo "Triggered Release Please workflow"
+85
View File
@@ -0,0 +1,85 @@
# Step 4: Triggers when the changelog PR is merged to release/candidate.
# Records last-release-sha and renames release/candidate to release/v{version}.
name: "Release: Finalize"
on:
pull_request:
types: [closed]
branches:
- release/candidate
permissions:
contents: write
pull-requests: write
jobs:
finalize:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- name: Check for release-please PR
id: check
env:
LABELS: ${{ toJson(github.event.pull_request.labels.*.name) }}
run: |
if echo "$LABELS" | grep -q "autorelease: pending"; then
echo "is_release_pr=true" >> $GITHUB_OUTPUT
else
echo "Not a release-please PR, skipping"
echo "is_release_pr=false" >> $GITHUB_OUTPUT
fi
- uses: actions/checkout@v4
if: steps.check.outputs.is_release_pr == 'true'
with:
ref: release/candidate
token: ${{ secrets.RELEASE_PAT }}
fetch-depth: 0
- name: Extract version from manifest
if: steps.check.outputs.is_release_pr == 'true'
id: version
run: |
VERSION=$(jq -r '.["."]' .github/.release-please-manifest.json)
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "Extracted version: $VERSION"
- name: Configure git identity from RELEASE_PAT
if: steps.check.outputs.is_release_pr == 'true'
env:
GH_TOKEN: ${{ secrets.RELEASE_PAT }}
run: |
USER_JSON=$(gh api user)
git config user.name "$(echo "$USER_JSON" | jq -r '.login')"
git config user.email "$(echo "$USER_JSON" | jq -r '.id')+$(echo "$USER_JSON" | jq -r '.login')@users.noreply.github.com"
- name: Record last-release-sha for release-please
if: steps.check.outputs.is_release_pr == 'true'
run: |
git fetch origin main
CUT_SHA=$(git merge-base origin/main HEAD)
echo "Release was cut from main at: $CUT_SHA"
jq --arg sha "$CUT_SHA" '. + {"last-release-sha": $sha}' \
.github/release-please-config.json > tmp.json && mv tmp.json .github/release-please-config.json
git add .github/release-please-config.json
git commit -m "chore: update last-release-sha for next release"
git push origin release/candidate
- name: Rename release/candidate to release/v{version}
if: steps.check.outputs.is_release_pr == 'true'
run: |
VERSION="v${STEPS_VERSION_OUTPUTS_VERSION}"
git push origin "release/candidate:refs/heads/release/$VERSION" ":release/candidate"
echo "Renamed release/candidate to release/$VERSION"
env:
STEPS_VERSION_OUTPUTS_VERSION: ${{ steps.version.outputs.version }}
- name: Update PR label to tagged
if: steps.check.outputs.is_release_pr == 'true'
env:
GH_TOKEN: ${{ github.token }}
run: |
gh pr edit ${{ github.event.pull_request.number }} \
--remove-label "autorelease: pending" \
--add-label "autorelease: tagged"
echo "Updated PR label to autorelease: tagged"

Some files were not shown because too many files have changed in this diff Show More