This is to avoid serialization issue for some fields that are not json serializable.
meanwhile restructure the debug logs in context cache manager for better debugging potential issues.
PiperOrigin-RevId: 811182492
AppDetails require two pieces of information:
1) Instructions
2) Tools
Both these pieces of information are gathered using the llm_request that was passed to the model. This approach, slightly invasive, ensures that we capture the "exact" instructions and tools that were given to the model.
PiperOrigin-RevId: 811180648
Details:
1. Data model for storing App Details (the agentic system)
As we move towards LLM as Judge metrics, we see that some of these metrics need information about the Agentic system that was used for inferencing. We add a data model to capture that.
2. Data model for Steps
We refine the concept of intermediate data. Previously it stored data in the form of a multiple lists, thereby losing out on the chronological information. This information is needed for some of the metrics. So we refine the concept of intermediate data as series of logical steps that an Agent Take.
PiperOrigin-RevId: 811122784
Merge https://github.com/google/adk-python/pull/2823
Description
This change introduces a tool_name_prefix attribute to McpToolset and McpToolsetConfig. This allows for adding a prefix to the
names of all tools within the toolset, which can help avoid naming collisions and provide better organization.
The implementation involves updating the McpToolset's __init__ and from_config methods to handle the new tool_name_prefix and
adding the corresponding field to McpToolsetConfig.
Testing Plan
A new unit test file has been added to ensure the functionality works as expected.
- `tests/unittests/tools/test_mcp_toolset.py`:
- The test_mcp_toolset_with_prefix test case verifies that the tool_name_prefix is correctly applied to the tool names
retrieved from the toolset.
- All tests were run via pytest and passed.
Related Issue
- Closes#2814
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2823 from shsha4:fix/issue-2814 e8e5b0d6d5f406d3875faf2229a96701725b7a5e
PiperOrigin-RevId: 810500616
Merge https://github.com/google/adk-python/pull/2458
**Summary**
Verifies that user-provided messages are always passed to the LLM as 'user' role, regardless of whether the role is explicitly set in types.Content. Before the current fix, if the LlmRequest from the user doesn't have the 'user' role, but has the user content, then the text is being replaced with the standard text - "Handle the requests as specified in the System Instruction." and the content from the user is completely ignored and not passed into the LLM.
**Code to replicate the problem**
```
from google.adk.agents import LlmAgent
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.genai.types import Content, Part
from google.adk.models.lite_llm import LiteLlm
from google.adk.models import LlmRequest
from google.genai import types
from pydantic import Field
import litellm
litellm._turn_on_debug()
import warnings
warnings.filterwarnings("ignore", category=UserWarning, message=".*InMemoryCredentialService.*")
import os
from dotenv import load_dotenv
# Load environment variables from the agent directory's .env file
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Define agent with output_key
root_agent = LlmAgent(
name="name_of_agent",
model=LiteLlm(model="azure/gpt-4o-mini"),
instruction="You are a customer agent to help the users with their concerns."
)
# --- Setup Runner and Session ---
app_name, user_id, session_id = "state_app", "user1", "session1"
session_service = InMemorySessionService()
runner = Runner(
agent=root_agent,
app_name=app_name,
session_service=session_service
)
print(f"Runner created for agent '{runner.agent.name}'.")
session = await session_service.create_session(
app_name=app_name,
user_id=user_id,
session_id=session_id
)
# --- Run the Agent ---
async def call_agent_async(query: str, runner, user_id, session_id):
user_message = Content(parts=[Part(text=query)])
async for event in runner.run_async(
user_id=user_id,
session_id=session_id,
new_message=user_message
):
print("event")
print(f" [Event]\n Author: {event.author}\n Type: {type(event).__name__}",
f"\n Final: {event.is_final_response()}\n Content: {event.content}")
return event
event = await call_agent_async("What is the capital of India.",runner=runner,user_id=user_id,session_id=session_id)
```
**Before the fix (current adk-python code output)**
```
00:29:24 - LiteLLM:DEBUG: utils.py:348 -
00:29:24 - LiteLLM:DEBUG: utils.py:348 - Request to litellm:
00:29:24 - LiteLLM:DEBUG: utils.py:348 - litellm.acompletion(model='azure/gpt-4o-mini', messages=[{'role': 'developer', 'content': 'You are a customer agent to help the users with their concerns.\n\nYou are an agent. Your internal name is "name_of_agent".'}, {'role': 'user', 'content': 'Handle the requests as specified in the System Instruction.'}], tools=None, response_format=None)
```
**After the fix (after resolving the fix)**
```
00:28:46 - LiteLLM:DEBUG: utils.py:349 -
00:28:46 - LiteLLM:DEBUG: utils.py:349 - Request to litellm:
00:28:46 - LiteLLM:DEBUG: utils.py:349 - litellm.acompletion(model='azure/gpt-4o-mini', messages=[{'role': 'developer', 'content': 'You are a customer agent to help the users with their concerns.\n\nYou are an agent. Your internal name is "name_of_agent".'}, {'role': 'user', 'content': 'What is the capital of India.'}], tools=None, response_format=None)
```
**Testing**
Following unit test is created to test the applied changes and added in the location as suggested in the guidelines.
adk-python\tests\unittests\models\test_base_llm.py
```
import pytest
from google.genai import types
from google.adk.models.llm_request import LlmRequest
from google.adk.models.lite_llm import _get_completion_inputs
@pytest.mark.parametrize("content_kwargs", [
# Case 1: Explicit role provided
{"role": "user", "parts": [types.Part(text="This is an input text from user.")]},
# Case 2: Role omitted, should still be treated as 'user'
{"parts": [types.Part(text="This is an input text from user.")]}
])
def test_user_content_role_defaults_to_user(content_kwargs):
"""
Verifies that user-provided messages are always passed to the LLM as 'user' role,
regardless of whether the role is explicitly set in types.Content.
The helper `_get_completion_inputs` should give normalize messages so that
explicit 'user' and implicit (missing role) are equivalent.
"""
llm_request = LlmRequest(
contents=[types.Content(**content_kwargs)],
config=types.GenerateContentConfig()
)
messages, _, _, _ = _get_completion_inputs(llm_request)
assert all(
msg.get("role") == "user" for msg in messages
), f"Expected role 'user' but got {messages}"
assert any(
"This is an input text from user." == (msg.get("content") or "")
for msg in messages
), f"Expected the user text to be preserved, but got {messages}"
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2458 from TanejaAnkisetty:bug/agent-user-content 381b01418d249b9e6bd91ebb518ff25339a8e47b
PiperOrigin-RevId: 809281620
Static instructions:
Always added to system instructions for context caching
Dynamic instructions:
Added to system instructions when no static instruction exists (for backward compatibility), OR inserted before last batch of continuous user content when static instructions exist
PiperOrigin-RevId: 809170679
1. add a context cache config in app level which will apply to all agents in the app
2. pass on cache config through invocation context to llm_reqeust
3. store cache metadata in llm_response
4. lookup old cache metadata from latest event for reusing old cache
5. create new cache if old cache cannot be reused
PiperOrigin-RevId: 809158578
Currently there is chance for Cloud Monitoring-related errors in logs during shutdown. Let's disable metrics part until it is fixed.
PiperOrigin-RevId: 808930635
The docstrings for `compaction_range` and `compacted_content` are updated to reflect that compaction is based on timestamp ranges rather than sequence IDs, and to use consistent terminology ("compacted" instead of "summarized").
PiperOrigin-RevId: 808770610
Merge https://github.com/google/adk-python/pull/2960
1. All in one authentication sample (has an IDP, Agent and the application) under `contributing/samples/authn-adk-all-in-one/`
2. Documented for all the steps.
3. OAuth 2.0 Authorization Code Grant type used by the agent.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2960 from nikhilpurwant:main dfcc821602d265c4ae7cc42eb1f5739beaad6f87
PiperOrigin-RevId: 808672120
This add `GoogleMapsGroundingTool`, a built-in tool for Gemini 2 models to ground query results with Google Maps. This tool operates internally within the model and is only available when using the VertexAI Gemini API.
PiperOrigin-RevId: 808650501
Provide a more efficient way to compact LLM context for better agentic performance.
* `app`: the top level abstraction for an ADK application. It contains an root agent, and plugins.
* `content_strategy`: the abstraction for selecting the contents for LLM request.
* `compaction_strategy`: the abstraction for compacting the events.
* Added `sequence_id` and `summary_range` in event class.
PiperOrigin-RevId: 808634224
Merge https://github.com/google/adk-python/pull/2937
**Closes #2936**
This Pull Request addresses the issue where `LlmAgent` outputs, when configured with `output_schema` and `tools`, were presenting escaped Latin characters (e.g., `\xf3` for `ó`) in the final response. This behavior occurred because `json.dumps` was being called with `ensure_ascii=True` (its default), which is not ideal for human-readable output, especially when dealing with non-ASCII characters common in many languages like Portuguese.
**Changes Proposed:**
* Modified the `_OutputSchemaRequestProcessor` in `src/google/adk/flows/llm_flows/_output_schema_processor.py` to explicitly set `ensure_ascii=False` when calling `json.dumps` for the `set_model_response` tool's output.
**Impact:**
This change ensures that all non-ASCII characters in the structured model response are preserved in their natural form, improving the readability and user experience of agent outputs, particularly for users interacting in languages with accented characters or other special symbols.
**Testing:**
The fix was verified locally by running an `LlmAgent` with an `output_schema` and confirming that responses containing Latin characters (e.g., "ação", "caminhão", "ícone") are now correctly displayed without escaping.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2937 from amenegola:fix/issue-2936-escape-chars 6cac00f97aa4cd8d8ccaa97ec5fffc74f57995dc
PiperOrigin-RevId: 808622892
- Add conformance command group with create subcommand
- Implement category/name/spec.yaml with generated-*.yaml files
- Support executing agents with queries and recording sessions
- Create test cases with recorded llm interactions and tool calls/results
Expected folder structure:
```
conformance_repo/
├── agents/ # Agent definitions - contains all config-based agents shared by test cases.
│ ├── single_basic/
│ ├── multi_basic/
│ └── single_tool_builtin/
│
└── tests/ # Test cases
├── core/ # Test category
│ ├── desc_001/ # Individual test case
│ │ ├── spec.yaml # Human-written specification
│ │ ├── generated-session.yaml
│ │ ├── generated-recordings.yaml
│ │ └── ... # Potential future generated files
│ ├── f_001/
│ │ ├── spec.yaml
│ │ ├── generated-session.yaml
│ │ ├── generated-recordings.yaml
│ │ └── ...
```
Help text:
```
-> % adk conformance create --help
Usage: adk conformance create [OPTIONS] [PATHS]...
Generate ADK conformance test YAML files from TestCaseInput specifications.
NOTE: this is work in progress.
This command reads TestCaseInput specifications from input.yaml files, executes the specified test cases against agents, and generates conformance test files with recorded agent interactions as
test.yaml files.
Expected directory structure: category/name/input.yaml (TestCaseInput) -> category/name/test.yaml (TestCase)
PATHS: One or more directories containing test case specifications. If no paths are provided, defaults to 'tests/' directory.
Examples:
Use default directory: adk conformance create
Custom directories: adk conformance create tests/core tests/tools
Options:
--help Show this message and exit.
```
PiperOrigin-RevId: 808609547
Corrected `CountInvocationPlugin` to be a class reference and added `ContextFilterPlugin` to limit the number of tool invocations kept in the context to 3.
PiperOrigin-RevId: 808591608
When start the server with `--extra_plugins=google.adk.cli.plugins.recordings_plugin.RecordingsPlugin`, it will trigger recording with expected state in session.
PiperOrigin-RevId: 808432022
This commit introduces a new ContextFilterPlugin which allows for filtering the LlmRequest contents before they are sent to the LLM. This helps in managing and potentially reducing the size of the LLM context.
The plugin provides two primary filtering mechanisms:
num_invocations_to_keep: Keeps only the specified number of the most recent user-model invocations. An invocation is defined as one or more user messages followed by a model response.
custom_filter: Allows for a user-defined callable to be applied to the contents for more flexible filtering.
Unit tests have been added to cover the different filtering scenarios, including:
Filtering by the last N invocations.
Filtering using a custom function.
Combining both filtering methods.
Handling cases with multiple user turns in a single invocation.
Ensuring no filtering occurs when options are not provided.
Gracefully handling exceptions from custom filter functions."
For example, when num_of_innovacations=2:
-----------------------------------------------------------
Contents:
{"parts":[{"text":"9"}],"role":"user"}
{"parts":[{"text":"I am sorry, I cannot fulfill this request. I need more information on what you would like me to do. I can roll a die or check prime numbers.\n"}],"role":"model"}
{"parts":[{"text":"1"}],"role":"user"}
{"parts":[{"text":"I am sorry, I cannot fulfill this request. I need more information on what you would like me to do. I can roll a die or check prime numbers.\n"}],"role":"model"}
{"parts":[{"text":"10"}],"role":"user"}
-----------------------------------------------------------
PiperOrigin-RevId: 808355316
Right now the bigquery sample agent is configured to run with OAuth, which requires some set up. This change makes it more readily usable, both locally and in AgentEngine, as Application Default Credentials (ADC) is easier to set up, and often local and AgentEngine environment already have it set up.
PiperOrigin-RevId: 808315879
Also moves the `Recordings` pydantic models into this plugins/ package.
Key features:
- Records LLM requests/responses and tool calls/results to YAML files in `generated-recordings.yaml`.
- Use session state to determine where to read and output recordings.
PiperOrigin-RevId: 807969100
Cloud Trace, Cloud Monitoring and Cloud Logging integrations are set up via OTel if otel_to_cloud CLI param/fast_api arg is provided.
This is similar to current Cloud Trace integration via trace_to_cloud, just extended to Monitoring and Logging as well.
PiperOrigin-RevId: 807385680
Cloud Trace, Cloud Monitoring and Cloud Logging integrations are set up via OTel if otel_to_cloud CLI param/fast_api arg is provided.
This is similar to current Cloud Trace integration via trace_to_cloud, just extended to Monitoring and Logging as well.
PiperOrigin-RevId: 807285744
Cloud Trace, Cloud Monitoring and Cloud Logging integrations are set up via OTel if otel_to_cloud CLI param/fast_api arg is provided.
This is similar to current Cloud Trace integration via trace_to_cloud, just extended to Monitoring and Logging as well.
PiperOrigin-RevId: 807230668
The `after_agent_callback` in plugin works similarly as the `after_agent_callback` in `base_agent.py`, e.g. it only append new content, but cannot modify the previous content.
PiperOrigin-RevId: 807162139
Similarity search tool supports similarity search on Spanner data by embedding a text query to a vector and run vector search with the embedded vector.
PiperOrigin-RevId: 806502499
Recent change to the updated A2A Client SDK broke the logging utilities. This updates those logging utilities to work with the new A2A SDK structure.
PiperOrigin-RevId: 806482017
Right now the tolls are always running against multi-region US by default. With this change the agent builder can scope the tools to data and compute in a particular BigQuery location.
PiperOrigin-RevId: 806473857
Update the bug report issue template to request minimal reproducible examples, error/stacktrace, clarify OS options, and include questions about LiteLLM usage and specific model details.
PiperOrigin-RevId: 806435953
The new test verifies that `output_audio_transcription` and `input_audio_transcription` attributes are unique to each `RunConfig` instance, preventing unintended side effects from modifying one instance.
PiperOrigin-RevId: 806405671
Switched the active model from `gemini-live-2.5-flash-preview` (for AI Studio) to `gemini-2.0-flash-live-preview-04-09` (for Vertex).
PiperOrigin-RevId: 806348640
Both are valid YAML, just with indent, it's more visually friend to see the data structure hierarchy.
Before
```
items:
- item1
- item2
- item3
```
After
```
items:
- item1
- item2
- item3
```
PiperOrigin-RevId: 806117290
The old live/bidi agents are using a cache to store context/history during agent transfer etc. As we have added support for session for live/bidi, we are now migrating the context/history cache to it. This improves scalability, efficiency and maintainability.
It introduces several changes:
* AudioTranscriber support is removed as now we are using native transcription from models.
* Transcription is returned as input_transcription/output_transcription fields and no longer as contents.
* We will return a new event with artifact references of file type of audio/pcm.(in addition to existing audio response event. So the users of this api need to do proper filtering here.)
PiperOrigin-RevId: 805997675
For advanced eval use cases, we do expect agent developers to have rubrics that are specific to an Eval Case and in some cases even specific to a single invocation/turn in the eval case conversation.
A separate PR will be created to consume this data model changes in ADK Eval.
PiperOrigin-RevId: 805588808
a. dump the discussion content to a tmp file first to avoid github redaction of environment variable
b. instruct the agent to use get_discussion_and_comments only when discussion content json is not available.
PiperOrigin-RevId: 805581573
Changes references from `gemini-1.5-flash` and `gemini-1.5-pro` to `gemini-2.5-flash` and `gemini-2.5-pro` in docstrings, default values, sample agents, and tests.
PiperOrigin-RevId: 805536434
Details:
- We plan on introducing Rubric based metrics in subsequent changes. This change introduces the data model needed that allows agent developer to provide rubrics.
- We also introduce a data model for the config that the eval system has been using for quite some time. It was loosely and informally described as a dictionary of metric names and expected thresholds. In this change, we actually formalize it using a pydantic data model, and extend it allow developers to specify rubrics as a part of their eval config.
What is a rubric based metric?
A rubric based metric is the assessment of a Agent's response (final or intermediate) along some rubric. This evaluation of agent's response significantly differs from the strategy where one has to provide a golden response.
PiperOrigin-RevId: 805488436
These tests verify that `ValueError` is raised when `Runner` is initialized without providing either an `app` instance or both `app_name` and `agent`.
PiperOrigin-RevId: 805427256
Merge https://github.com/google/adk-python/pull/2864
**Reason for this change:**
Multiple typos were found in comments, docstrings, and code throughout the codebase, which could lead to confusion and reduce code readability.
**Changes made:**
Fixed the following typos across 8 files:
1. contributing/samples/adk_answering_agent/utils.py:130: "extention" → "extension"
2. llms-full.txt:15171: "fuction" → "function"
3. src/google/adk/a2a/converters/part_converter.py:
- Line 96: "Conver" → "Convert", "reponse" → "response"
- Line 99: "suervice" → "service"
- Line 100: "accordinlgy" → "accordingly"
- Line 191: "Conver" → "Convert", "reponse" → "response"
- Line 195: "accordinlgy" → "accordingly"
4. src/google/adk/agents/base_agent.py:568: "custome" → "custom"
5. src/google/adk/evaluation/agent_evaluator.py:572: "Retruns" → "Returns"
6. src/google/adk/flows/llm_flows/basic.py:55: "outoput_schema" → "output_schema"
7. src/google/adk/flows/llm_flows/contents.py:136: "fuction_response" → "function_response"
8. src/google/adk/models/google_llm.py:138: "gemini_llm_connecton.py" → "gemini_llm_connection.py"
**Impact:**
This change will:
- Improve code documentation clarity and professionalism
- Make comments, docstrings, and code more readable and accurate
- Help prevent confusion for developers reading the code
- Ensure consistency in terminology throughout the codebase
This is a non-breaking change that only affects comments, documentation strings, and improves code clarity.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2864 from ammmr:chore-fix-typos 3cea9fcf6f21edb006b63e9258d2b82930dd961d
PiperOrigin-RevId: 805227784
The `agent-triage-pull-request` job will now only run if the pull request does not have the 'bot triaged' or 'google-contributor' labels, avoiding redundant and unnecessary triage actions.
PiperOrigin-RevId: 804732073
Use the A2A Python SDK for client support for A2A Remote clients. This enables A2A based agents that use gRPC or RESTful interfaces, as well as the jsonrpc support. This also simplifies creation of clients and provides simpler mechanisms to inject credentials and observability into the remote agent interactions.
PiperOrigin-RevId: 804711466
Changed default values for `session_service`, `artifact_service`, and `run_config` from instances of mutable classes to `None`. Instances are now created within the function body if the argument is not provided, preventing unexpected shared state across function calls.
PiperOrigin-RevId: 804624564
The system instructions for agent transfer now include a NOTE section that lists all agents available for the `transfer_to_agent` function. This also has the target agents and, if there is one that applies, the parent agent. New unit tests are added to verify the correct generation of this NOTE.
PiperOrigin-RevId: 804569691
Changed default values for `session_service`, `artifact_service`, and `run_config` from instances of mutable classes to `None`. Instances are now created within the function body if the argument is not provided, preventing unexpected shared state across function calls.
PiperOrigin-RevId: 804560641
Merge https://github.com/google/adk-python/pull/1629
close https://github.com/google/adk-python/issues/2170
### Summary
This PR introduces `GkeCodeExecutor`, a new code executor that provides a secure and scalable method for running LLM-generated code by leveraging GKE Sandbox. It serves as a robust alternative to local or standard containerized executors by leveraging the **GKE Sandbox** environment, which uses gVisor for workload isolation.
For each code execution request, it dynamically creates an ephemeral Kubernetes Job with a hardened Pod configuration, offering significant security benefits and ensuring that each code execution runs in a clean, isolated environment.
### Key Features of GkeCodeExecutor
* **Dynamic Job Creation**: Uses the Kubernetes `batch/v1` API to create a new Job for each code snippet.
* **Secure Code Mounting**: Injects code into the Pod via a temporary `ConfigMap`, which is mounted to a read-only file.
* **gVisor Sandboxing**: Enforces execution within a `gvisor` runtime for kernel-level isolation.
* **Hardened Security Context**: Pods run as non-root with all Linux capabilities dropped and a read-only root filesystem.
* **Resource Management**: Applies configurable CPU and memory limits to prevent abuse.
* **Automatic Cleanup**: Uses the `ttl_seconds_after_finished` feature on Jobs for robust, automatic garbage collection of completed Pods and Jobs.
* **Node Scheduling**: The executor uses Kubernetes `tolerations` in its Pod specification. This allows the k8s scheduler to place the execution Pod onto a **_pre-configured_** gVisor-enabled node.
* **Module Integration**: The `GkeCodeExecutor` is registered in the `code_executors/__init__.py`, making it available for use by agents. The `ImportError` handling is configured to check for the required `kubernetes` SDK.
### Execution Flow:
1. Agent invokes `GkeCodeExecutor` with the LLM-generated code.
2. The `GkeCodeExecutor` will `execute_code` – creates a temporary `ConfigMap`, and then create a k8s `Job` to run it.
3. This Job runs a standard `python:3.11-slim` container. The image is pulled once to the node and cached. The Job will mount the ConfigMap as `/app/code.py`
4. The GkeCodeExecutor will monitor the Job to completion, fetch `stdout/stderr` logs from the container, return `CodeExecutionResult` to the LlmAgent, and ensure all temp resources are deleted.
5. The calling agent formats the result and provides a final response to the user. If the result contains error, it will retry up to `error_retry_attempts` times.
PiperOrigin-RevId: 804511467
This includes:
- Test verifying multiple spans are written during E2E runner execution.
- Regression tests for the "ContextVar was created in a different Context" exceptions caused by the interplay of context based instrumentation and async generators getting indeterminately suspended.
PiperOrigin-RevId: 804333483
- Added `tests/unittests/apps/test_apps.py` with basic tests for `App` initialization.
- Modified `tests/unittests/test_runners.py` to include a test that verifies `Runner` raises a `ValueError` when both `app` and `app_name` are provided during initialization.
PiperOrigin-RevId: 803556826
This change introduces type descriptions for the functions which convert between A2A and GenAI `Part`s. It then allows passing instances of those functions to the various A2A-related functions/classes, effectively allowing users to inject their own logic for how part conversion should occur.
The benefit of this pattern is that users can create decorators around the core `Part` conversion logic, which allows them to intercept the cases they care about while delegating the ones they do not to the core converter. This is a pattern we use a lot in the A2A Python SDK.
One example where this type of logic is useful is for extensions: this allows extension logic to, for example, interpret an A2A DataPart into a FunctionResponse using extension-specific logic.
PiperOrigin-RevId: 803186799
The convention:
- If some fields(like plugin) are defined both at root_agent and app, then a error will be raised.
- app code should be located within agent.py.
- an instance named app should be created
PiperOrigin-RevId: 803155804
Before this change, other agent's reply with thought will still be inserted in the outgoing LlmRequest due to the wrong `else` statement for calling all other type of part.
This commit also refactors test_contents.py to be behavior-oriented tests, instead of implementation-oriented, and add more test cases to cover expected scenarios.
The tests are divided into the following files with different focus:
- test_contents.py: covers the basic logic of event filter;
- test_contents_branch.py: covers the behavior related to branch, which takes effect when ParallelAgent is used.
- test_contents_other_agent.py: covers the retelling behavior to include other agents' reply as context for the current agent.
- test_contents_function.py: covers the function_call/function_response rearrangement logic mainly for `LongRunningFunctionTool`.
PiperOrigin-RevId: 802759821
Before this change: `thought` flags was incorrectly removed if the current agent enables BuiltInPlanner.
After this change:
- When it's BuiltInPlanner, keep the thought flag in content history, so that model has full context of its previous thinking.
- When it's PlanReactPlanner, removes the `thought` flag in content history, so that model sees as-is when the content was generated.
PiperOrigin-RevId: 802737130
Merge https://github.com/google/adk-python/pull/2791Fixes#2789
## Summary
Forward `state_delta` from the FastAPI `/run` request to `Runner.run_async(...)`, aligning behavior with the documented
API and the `/run_sse` endpoint.
## Why
The documentation for `/run` explicitly includes:
> `state_delta` (object, optional): A delta of the state to apply before the run.
However, the non‑SSE `/run` handler did not pass this value through, so `Runner.run_async` always received `None`. The
`/run_sse` path already forwarded it correctly.
## Changes
- `src/google/adk/cli/adk_web_server.py`
- Add `state_delta=req.state_delta` to the "/run" handler’s `runner.run_async(...)` call.
- `tests/unittests/cli/test_fast_api.py`
- Add `test_agent_run_passes_state_delta` to test the fix.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2791 from pguerra-ce:fix-state-delta-missing-in-run 83eec8d28b80757e24ae900285eb59530863adbd
PiperOrigin-RevId: 802703072
The convention:
- If some fields(like plugin) are defined both at root_agent and app, then a error will be raised.
- app code should be located within agent.py.
- an instance named app should be created
PiperOrigin-RevId: 801252329
The convention:
- If some fields(like plugin) are defined both at root_agent and app, then a error will be raised.
- app code should be located within agent.py.
- an instance named app should be created
PiperOrigin-RevId: 801103084
The convention:
- If some fields(like plugin) are defined both at root_agent and app, then a error will be raised.
- app code should be located within agent.py.
- an instance named app should be created
PiperOrigin-RevId: 801084463
This will allow restricting BigQuery SQL executions to the specified project. The agent/LLM should resolve the `project_id` param for tools like `execute_sql` and sometimes they can resolve it to an unexpected value due to hallucination or ambiguity. This guardrail will protect against that situation.
PiperOrigin-RevId: 801039685
The existing `LongRunningTool` does not define a programmatic way to provide & validate structured input, also it relies on LLM to reason and parse the user's response.
For a quick start, annotate the function with `FunctionTool(my_function, require_confirmation=True)`. A more advanced flow is shown in the `human_tool_confirmation` sample.
The new flow is similar to the existing Auth flow:
- User request a tool confirmation by calling `tool_context.request_confirmation()` in the tool or `before_tool_callback`, or just using the `require_confirmation` shortcut in FunctionTool.
- User can provide custom validation logic before tool call proceeds.
- ADK creates corresponding RequestConfirmation FunctionCall Event to ask user for confirmation
- User needs to provide the expected tool confirmation to a RequestConfirmation FunctionResponse Event.
- ADK then checks the response and continues the tool call.
PiperOrigin-RevId: 801019917
Use full media types (image/jpeg, video/mp4, application/pdf) instead of suffixes (jpeg/mp4/pdf) when constructing LiteLLM payloads
This fxes compatibility with providers that validate media types (Anthropic)
Updated and added unit tests to assert full MIME types for image/video/pdf
PiperOrigin-RevId: 800685204
original tests assert too strict time boundary, now we only assert the parallel execution time should be less than sequential execution time
PiperOrigin-RevId: 800563929
The transcription change breaks the multi-agent transfer during live/bidi.
Updates `GeminiLlmConnection` to populate the `content` field of `LlmResponse` with `types.Content` and `types.Part` objects for both input and output transcriptions, instead of using dedicated transcription fields. Also removes a debug print from `audio_cache_manager.py`.
the transcription is not fully ready to be used yet so roll back the transcription change.
PiperOrigin-RevId: 799851950
- Keep original class names for backward-compatibility.
- Log warning if user instantiate the classes with original names.
- New names are more aligned with MCP SDKs convention.
PiperOrigin-RevId: 799777320
Merge https://github.com/google/adk-python/pull/2563
Currently in adk deploy cloud_run or gke, the dockerfile copies the agent code after the file permission is set. This can lead to file permission not being set correctly for the container to open and read the file.
This PR will make sure the files are copied with the permission of the user that is set in the container.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2563 from moficodes:deploy-docker d7f6df4d893af75b360e6d96ffd2640ce6076ca2
PiperOrigin-RevId: 799371070
Merge https://github.com/google/adk-python/pull/2544
The command `adk deploy cloud_run` supports limited `gcloud run deploy` args 😢.
Which makes the command fine for simple deployments...
It should support all current and future Cloud Run deployment args for the command to be widely adopted.
This can easily be done by passing through all extra args passed to `adk deploy cloud_run` to gcloud...
This PR assumes any extra args/flags passed after `AGENT_PATH` are gcloud flags.
## Example
```sh
# ADK flags
adk deploy cloud_run \
--project=$GOOGLE_CLOUD_PROJECT \
--region=$GOOGLE_CLOUD_LOCATION \
$AGENT_PATH \
# Use the -- separator for gcloud args
-- \
--min-instances=2 \
--no-allow-unauthenticated
```
This gives full Cloud Run feature support to ADK users 🤖🚀
## Test Plan
To test you can just build locally or pip install feature branch directly:
```
uv venv
uv pip install git+https://github.com/jackwotherspoon/adk-python.git
```
Deploy to Cloud Run using additional arguments following `AGENT_PATH`, such as `--min-instance=2` or `--description="Cloud Run test"`:
```sh
uv run adk deploy cloud_run \
--project=$GOOGLE_CLOUD_PROJECT \
--region=$GOOGLE_CLOUD_LOCATION \
--with_ui \
$AGENT_PATH \
-- \
--labels=test-label=adk \
--min-instances=2
```
You can click on the Cloud Run service after deployment and check the service yaml, you should see the additional label etc.
<img width="1612" height="622" alt="image" src="https://github.com/user-attachments/assets/596a260a-0052-460b-9642-c18900ccf7c9" />
Fixes https://github.com/google/adk-python/issues/2351
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2544 from jackwotherspoon:main 184a4d73f8dbe6f565ff92cf1c1fe69bb163de5e
PiperOrigin-RevId: 799252544
Merge https://github.com/google/adk-python/pull/2409
Description:
This PR Fixes: #2407
The AgentTool in /google/adk/tools/agent_tool.py uses a hardcoded user_id='tmp_user' when creating a new session for the agent it wraps. This happens within the run_async method.
code snippet
... @override async def run_async( self, *, args: dict[str, Any], tool_context: ToolContext, ) -> Any: ... session = await runner.session_service.create_session( app_name=self.agent.name, user_id='tmp_user', # <-- This is hardcoded state=tool_context.state.to_dict(), ) ...
Why is this a problem?
This hardcoding breaks the chain of user identity. When a parent agent calls a sub-agent via the AgentTool, the original user_id is lost. Any tool or logic inside the sub-agent that needs to perform user-specific actions (e.g., accessing user data from a database, retrieving user-specific memory, checking permissions) will fail or operate on the wrong context because it receives 'tmp_user' instead of the actual user's ID.
Impact:
This prevents the creation of robust, multi-agent applications where user context must be maintained across different agents and tools. It limits the utility of AgentTool to only stateless sub-agents that do not require user-specific information.
Suggested Fix:
The user_id should be retrieved from the parent context, which is available via the tool_context parameter passed into run_async. The create_session call should be updated to use the dynamic user_id from the parent session.For example, the fix might involve accessing the user ID from the tool_context.
code-snippet
session = await runner.session_service.create_session( app_name=self.agent.name, user_id=tool_context._invocation_context.user_id, state=tool_context.state.to_dict(), )
To Reproduce
Steps to reproduce the behavior:
To reproduce this bug, we need to set up a two-agent system: a ParentAgent that calls a ChildAgent using the AgentTool. The ChildAgent will have a tool designed to simply return the user_id it receives from its context.
Expected behavior
It should return the user_id of the user calling the agent,
but, in current situation we are getting tmp_user
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2409 from akshaypachpute-1998:fix-issue-2407-agent-tool-context-propogation 0c3e8656fdf11386e3ab13a3a1f2df99a396dbd1
PiperOrigin-RevId: 798315832
Merge https://github.com/google/adk-python/pull/2641
This PR adds a custom `User-Agent` header to all requests made via `RestApiTool`. This allows backend services to identify traffic originating from the ADK. The header format is `google-adk/<version> (tool: <tool_name>)`, where `<version>` is the current version of the `google-adk` package, fetched dynamically from `google.adk.version`, and `<tool_name>` is the name of the specific `RestApiTool` instance.
**Associated Issue**
Fixes#2676
**Testing Plan**
**Unit Tests**
I ran the full suite of unit tests locally to ensure the changes did not introduce any regressions. All tests passed successfully.
```bash
$ pytest ./tests/unittests
================================= 4202 passed, 2459 warnings in 44.68s ====================
```
The warnings are related to existing experimental features and are not affected by this change.
**Manual End-to-End (E2E) Test**
I performed a manual test to ensure the integrated flow works as expected.
* **Setup:** Created a clean virtual environment (`~/venvs/adk-e2e-test`) and installed the locally built `google-adk` package using `uv venv --seed` and `pip install dist/google_adk-*.whl`. Ran a custom `mock_server.py` script (using Flask) in one terminal to listen for requests and print headers. Ran a custom `run_test_tool.py` script in a second terminal to send a request using the modified `RestApiTool`.
* **Execution:** The `run_test_tool.py` script successfully sent a POST request to the mock server's `/test` endpoint. The mock server received the request and printed the headers.
**`run_test_tool.py` Output:**
```json
{
"message": "Request received successfully!"
}
```
**`mock_server.py` Output (Headers):**
```text
--- Request Received ---
Headers:
Host: 127.0.0.1:8000
User-Agent: google-adk/1.12.0 (tool: TestTool)
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Type: application/json
Content-Length: 2
------------------------
```
The `User-Agent: google-adk/1.12.0 (tool: TestTool)` header confirms the change is working as intended, dynamically fetching the package version and including the tool name.
**Checklist**
* [x] Associated issue linked
* [x] Unit tests passed
* [x] End-to-end test performed and results documented
* [x] Code formatted with `./autoformat.sh`
---
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2641 from rcsantana777:feat/add-user-agent a9a9375306c18bb7ba501276cbf76693e70a87ad
PiperOrigin-RevId: 798232385
So far we had a default docstring for the `execute-sql` tool and for non-default write modes we were concatenating more content to it. This was working fine in Python 3.9-3.12 but broke in Python 3.13 because of a nuanced difference in the string concatenation to the `__doc__` property of a function b/433914562#comment4. This change makes the docstring management more robust and readable.
PiperOrigin-RevId: 797843736
This can help to provide more context and information about the table, like parent-child relationship, and row deletion policy etc.
PiperOrigin-RevId: 797562858
Introduce `DynamicPickleType` to handle session actions, using sqlalchemy-spanner `SpannerPickleType` when the database dialect is Spanner.
Connects to a Spanner database to store session data persistently in tables.
# Example using Spanner database:
`session_service = DatabaseSessionService(db_url="spanner+spanner:///projects/project-id/instances/instance-id/databases/database-id")`
# Example adk web command:
`adk web --session_service_uri="spanner+spanner:///projects/project-id/instances/instance-id/databases/database-id"`
PiperOrigin-RevId: 797416610
Merge https://github.com/google/adk-python/pull/2212
This PR closes issue #2202
ADK was not parsing the required attribute when using LiteLLM, letting the LLM decide what is required vs not, not respecting function definitions.
## Test Plan
There's a fork of adk-python that is being running live for over 2 weeks in our production environment with millions of requests per day.
Below you can find a screenshot of the unit tests passing. I've also added one change to the test cases to cover this scenario
<img width="1904" height="483" alt="image" src="https://github.com/user-attachments/assets/5a6eb069-63ae-45a3-baca-6b01543f56fb" />
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2212 from thiagosalvatore:main 7de4037d8016389313f3fb22df40c12bac578523
PiperOrigin-RevId: 797393698
VertexAiCodeExecutor and ContainerCodeExecutor request additional dependencies, lazy load them so that when users import other names, they won't get impacted if they don't had those additional dependencies installed.
Original codes swallow the exception and log a debug log is wrong and awkward, should follow the same style as what we did in https://github.com/google/adk-python/blob/main/src/google/adk/tools/retrieval/__init__.py
PiperOrigin-RevId: 796969332
Checked with local wheel and worked as intended. The harness shows suppression works: 0 warnings for all true-like values.
This CL adds ADK_DISABLE_EXPERIMENTAL_WARNING to let the users to suppress warning messages from features decorated with @experimental.
Previously, using experimental features would always trigger a UserWarning. This change creates a way to disable these warnings, which can be good to stop flooding logs.
The warning is suppressed if ADK_DISABLE_EXPERIMENTAL_WARNING is set to a truthy value such as "true", "1", "yes", or "on" (case-insensitive).
Added unit tests to make sure:
Warning suppression for functions and classes when the env var is set.
Case-insensitivity and various truthy values for the env var.
Loading the env var from a .env file.
PiperOrigin-RevId: 796649404
* feat: adding build image to deploy cloud_run options
Gives the ability for a user to set the build image for the deployment step to Cloud Run. Currently it is hard coded to python:3.11-slim, and this is still the default, but this allows that value to be overriden.
* fix: applied formatting scripts
testing:
Added tests to ensure the behavior of the cli remains consistent with when used or omitted.
* chore: next time run the formatter before you commit.
---------
Co-authored-by: Ivan Cheung <ivans.mailbox@gmail.com>
This change keeps dependencies to their major versions, but for the pre 1.0.0 releases pinned to minor releases as they could have breaking changes.
PyYAML: Version 7.0 is in development and could have breaking changes
absolufy-imports: The package is archived and no longer maintained.
anyio: Follows SemVer, so version 5.0 could have breaking changes.
authlib: Follows a SemVer-like pattern, so version 2.0 could have breaking changes.
click: A mature library, version 9.0 is the expected boundary for breaking changes.
fastapi: As a pre-1.0 library, the next minor release could have breaking changes.
google-api-python-client: Although in maintenance, version 3.0 could still have breaking changes.
google-cloud-aiplatform: Follows SemVer, so breaking changes are expected in version 2.0.
google-cloud-secret-manager: A stable Google library, version 3.0 could lead to breaking changes.
google-cloud-speech: A stable Google library, version 3.0 could lead to breaking changes.
google-cloud-storage: A stable Google library.
google-genai: As an official Google SDK, version 2.0 is the expected boundary for breaking changes.
graphviz: As a pre-1.0 library, the next minor release could have breaking changes.
mcp: As an SDK, version 2.0 is the boundary for potential breaking changes.
opentelemetry-api: Follows SemVer; version 2.0 could have breaking changes.
opentelemetry-exporter-gcp-trace: It's tied to the v1 OpenTelemetry API, so version 2.0 would likely be a breaking change.
opentelemetry-sdk: It's coupled to the v1 API, so version 2.0 would likely be a breaking change.
pydantic: This stops upgrades to the incompatible version 3.0 after its major 2.0 rewrite.
python-dateutil: Follows to SemVer, making version 3.0 the boundary for potential breaking changes.
python-dotenv: Locks to stable version 1.0 major release.
requests: As a more mature library, version 3.0 is boundary for breaking changes.
sqlalchemy: This locks the dependency to the stable version 2.0 API after its major rewrite.
starlette: As a pre-1.0 library, the next minor release could have breaking changes.
tenacity: This is a mature library, version 9.0 is boundary for breaking changes.
typing-extensions: Major versions are tied to large typing changes in Python itself.
tzlocal: The library has a history of introducing breaking API changes between major versions.
uvicorn: As a pre-1.0 library, the next minor release could have breaking changes.
watchdog: As a stable library, version 7.0 could have breaking changes.
websockets: Follows SemVer, so version 16.0 is the boundary for breaking changes.
PiperOrigin-RevId: 794677571
Verified with uv on Python 3.12 and 3.13 using the same ignores as CI.
3.12:
uv python install 3.12 && uv venv --python 3.12 .venv && source .venv/bin/activate
uv sync --extra test --extra eval --extra a2a
python -m pytest tests/unittests --ignore=tests/unittests/artifacts/test_artifact_service.py --ignore=tests/unittests/tools/google_api_tool/test_googleapi_to_openapi_converter.py
3.13: repeated the above with 3.13 (separate env)
Result: All unit tests passed
PiperOrigin-RevId: 794669437
Corrects a typo in the `StreamableHTTPConnectionParams` docstring, changing "SSE" to "Streamable HTTP" to accurately reflect the referenced client.
PiperOrigin-RevId: 794424727
For Vertex model backend, we send response back. This doesn't work for streaming tools that the return type is AsyncGenerator. So the fix here is to ignore the return type when it's AsyncGenerator.
We can't distinguish streaming vs non-streaming tool with AsyncGenerator though as LiveRequestQueue is optional in streaming tool.
Adds an `ignore_response` option to `build_function_declaration` to skip including the return type in the function declaration. This is enabled for tools that return `AsyncGenerator`, as the model does not yet support understanding these return types, while streaming tools can still handle them. Also, removes redundant return statements in `_get_mandatory_params`.
PiperOrigin-RevId: 794392846
This is to address the name conflict issue of tools returned by different toolset. Mainly it's to give each toolset a namespace.
We have a flag `add_tool_name_prefix` to decide whether to apply this behavior
We have a `tool_name_prefix` to let client specify a custom prefix, if not set , toolset name will be used as prefix.
PiperOrigin-RevId: 794306796
Merge https://github.com/google/adk-python/pull/1815
fix: path parameter extraction for complex Google API endpoints
- Fix GoogleApiToOpenApiConverter to handle path parameters in complex endpoints like /v1/documents/{documentId}:batchUpdate
- Use Google Discovery Document 'location' field
- Add comprehensive test suite for Google Docs batchUpdate functionality
- Verify parameter location handling for complex endpoint patterns
- Test schema validation for BatchUpdateDocumentRequest/Response
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1815 from goldylocks87:fix-issue-1814-path-parameter-extraction af5508ec6975b1ccbc34931a0041e422ee259c16
PiperOrigin-RevId: 794301898
Spanner toolset support basic operations to interact with Spanner table metadata and query results.
Consolidate BigQueryTool into generic GoogleTool, so that BigQueryToolset and SpannerToolset can share.
PiperOrigin-RevId: 794259782
The issue was caused by a breaking change in Python 3.13's inspect.cleandoc() function that made it more conservative about whitespace handling:
Root Cause:
- Python 3.12-: inspect.cleandoc() used line.lstrip() - strips all whitespace (spaces, tabs, etc.)
- Python 3.13+: inspect.cleandoc() uses line.lstrip(' ') - strips only space characters
PiperOrigin-RevId: 793921360
Demonstrates intelligent triage system with root planning agent and parallel
execution agents.
Use session state to store the execution plan and coordinate with other specialized agents.
Check out README.md for more details.
PiperOrigin-RevId: 793884758
1. Allow developers to specify output schema and tools together.
2. If both are specified, do the following:
2.1 Do not set output schema on the model config
2.2 Add a special tool called set_model_response(result)
2.3 `result` has the same schema as the requested output_schema
2.4 Instruct the model to use set_model_response() to output its final result, rather than output text directly.
2.5 When the set_model_response() is called, ADK will extract its content and put it in a text part, so the client would treat it as the model response.
PiperOrigin-RevId: 792686011
The connection_params argument in the constructor is split into four arguments in the config class because some of them have identical fields. In order to identify which is which, a separate name is more convenient.
PiperOrigin-RevId: 791965995
original codes try to eagerly import VertexAiRagRetrieval while it doesn't want to raise error if client try to import other names in this package and dependencies of VertexAiRagRetrieval is missing. so it swallow the import error which doesn't make sense, given vertex sdk is a must have for VertexAiRagRetrieval, we should fail fast.
this fix achieve the same purpose but fail fast if client try to import VertexAiRagRetrieval from this package and miss certain dependencies (e.g. vertex sdk)
PiperOrigin-RevId: 791759776
Previous implementation doesn't pass the actual handle to server. Now we cache the handle and pass it over when reconnection happens.
To enable:
run_config = RunConfig(
session_resumption=types.SessionResumptionConfig(transparent=True)
)
PiperOrigin-RevId: 791308462
1. given we are running parallel functions in one event loop (one thread) , we should use async lock instead of thread lock
2. test three kind of functions:
a. sync function
b. async function that doesn't yield
c. async function that yield
PiperOrigin-RevId: 791255012
Merge https://github.com/google/adk-python/pull/2327
`adk run --help` (adk 1.9.0)
```
--replay FILE The json file that contains the initial state of the
session and user queries. A new session will be created
using this state. And user queries are run againt the
newly created session. Users cannot continue to interact
with the agent.
```
```
$ git grep againt
src/google/adk/cli/cli_tools_click.py: " queries are run againt the newly created session. Users cannot"
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2327 from ftnext:fix-typo-run-replay-help 77cae65a235d9119810fe3d209910562672713c8
PiperOrigin-RevId: 790872246
1. if a function has no return type annotation, we should treat it as returning any type
2. we use empty schema (with `type` as None) to indicate no type constraints and this is already supported by model server
PiperOrigin-RevId: 789808104
Due to reasons that are being investigated, some of the recent changes got unintentionally reverted. We are adding those back in this PR.
PiperOrigin-RevId: 789384063
GitHub workflows triggered by `pull_request` events from forked repositories do not have access to secrets by default due to security considerations.
PiperOrigin-RevId: 789011890
The test test_token_exchange_not_supported was slow because of an incorrect monkeypatch target. The test was patching google.adk.auth.auth_handler.AUTHLIB_AVAILABLE, but the actual OAuth2 exchange logic uses a different AUTHLIB_AVAILABLE variable in google.adk.auth.exchanger.oauth2_credential_exchanger.
What was happening:
Test set auth_handler.AUTHLIB_AVAILABLE = False
AuthHandler.exchange_auth_token() called OAuth2CredentialExchanger.exchange()
But oauth2_credential_exchanger.AUTHLIB_AVAILABLE was still True
The exchanger attempted real OAuth2 token exchange with client.fetch_token()
This made actual network calls to OAuth2 endpoints, causing timeouts and delays
PiperOrigin-RevId: 788576949
This agent will post a comment if the PR is not following our contribution guides or add a label and reviewer for the PR if it passes the guide check.
PiperOrigin-RevId: 788511767
This endpoint could be used by ADK Web to dynamically know:
- What are the available eval metrics in an App
- A description of those metrics
- A value range supported by those metrics
We also update the metric registry to make it mandatory to supply these details. The goal is to improve usability and interpretability of the eval metrics.
PiperOrigin-RevId: 787277695
Merge https://github.com/google/adk-python/pull/869
How to reproduce the error:
```
from google.adk.code_executors import UnsafeLocalCodeExecutor
from google.adk.code_executors.code_execution_utils import CodeExecutionInput
result = UnsafeLocalCodeExecutor().execute_code(
invocation_context=None,
code_execution_input=CodeExecutionInput(
code='''
import math
def pi():
return math.pi
print(pi())
'''
)
)
print(result)
```
output:
```
CodeExecutionResult(stdout='', stderr="name 'math' is not defined", output_files=[])
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/869 from qieqieplus:main 63f557bbd3b7aa5c2801f5cc9e022d3364177308
PiperOrigin-RevId: 787145189
Merge https://github.com/google/adk-python/pull/2109Fixes#2105
## Problem
When integrating Google ADK with Langfuse using the @observe
decorator, the usage details displayed in Langfuse web UI were
incorrect.
The root cause was in the telemetry implementation where
total_token_count was being mapped to gen_ai.usage.output_tokens
instead of candidates_token_count.
- Expected mapping:
- candidates_token_count → completion_tokens (output tokens)
- prompt_token_count → prompt_tokens (input tokens)
- Previous incorrect mapping:
- total_token_count → completion_tokens (wrong!)
- prompt_token_count → prompt_tokens (correct)
## Solution
Updated trace_call_llm function in telemetry.py to use
candidates_token_count for output token tracking instead of
total_token_count, ensuring proper token count reporting to
observability tools like Langfuse.
## Testing plan
- Updated test expectations in test_telemetry.py
- Verified telemetry tests pass
- Manual verification with Langfuse integration
## Screenshots
**Before**
<img width="1187" height="329" alt="Screenshot from 2025-07-22 20-20-33" src="https://github.com/user-attachments/assets/ad5fc957-64a2-4524-bd31-0cebb15a5270" />
**After**
<img width="1187" height="329" alt="Screenshot from 2025-07-22 20-21-40" src="https://github.com/user-attachments/assets/3920df2a-be75-47e0-9bd0-f961bb72c838" />
_Notes_: From the screenshot, there's another problem: thoughts_token_count field is not mapped, but this should be another issue imo
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2109 from tl-nguyen:fix-telemetry-token-count-mapping 3d043f558b5f8bcb2c6e0370e2cc4c0ff25d1f4a
PiperOrigin-RevId: 786827802
Merge https://github.com/google/adk-python/pull/2148
This PR fixes#2071 exception string from `pip install google-adk[eval]` to `pip install "google-adk[eval]"` which makes it compatible for all the bash, zsh and other terminals
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2148 from kavinkumar807:fix-module-not-found-exception-string-in-eval 914281006a0e162665c0933d0c0ee0c37eb397cf
PiperOrigin-RevId: 786752261
This commit adds support for the session resumption configuration in the run_config.
The SessionResumptionConfig is added to RunConfig to allow the user to set up a configuration for session resumption(only transparent mode for now).
There are two modes of session resumption: manual and transparent. In manual mode, you have to manually bookkeeping the session information and restarts the session which is tricky to do right now. In transparent mode, the server does the bookkeeping for you and no hassle on ADK side. For now, the transparent mode should be enough.
Also, added the relevant unit tests to check that every possible configuration is set properly and the run_config is correctly populated.
This is needed for supporting the new session resumption feature.
PiperOrigin-RevId: 786549455
This plugin helps printing all critical events in the console. It is not a replacement
of existing logging in ADK. It rather helps terminal based debugging by showing all logs in the console, and serves as a
simple demo so everyone could develop their own plugins.
PiperOrigin-RevId: 786470637
This CL add new callbacks in plugin system:
- `on_tool_error_callback`
- `on_model_error_callback`
This allow the user to create plugins that can handle errors.
PiperOrigin-RevId: 786469646
Merge https://github.com/google/adk-python/pull/2138
This missing space leads to an error when deploying to cloud_run that says "No option --a2a/apps/agents"
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/2138 from andrewlarimer:fix--add-space-to-allow-adk-deploy-cloud_run---a2a 47831f10e1f7f6c27b5f6b8c102b2f7db4619778
PiperOrigin-RevId: 786459787
With this change we ensure that all three eval entry points, web, cli and pytest use the common LocalEvalService.
Updates to web and cli happened in a previous change.
PiperOrigin-RevId: 786445632
Mainly it's due to GenAI sdk changed their header of genai SDK versions, we have UT to verify that ADK or ADK users won't override their headers. Updated the header accordingly in the UT.
PiperOrigin-RevId: 786334741
Please set --log_level to DEBUG, if you are interested in having those API request and responses in logs.
NOTE: Generally it is not recommended to have DEBUG log level for services that run in a production setting. It is our recommendation to only use DEBUG log level in a debug or development setting.
PiperOrigin-RevId: 785972338
Merge https://github.com/google/adk-python/pull/1959
### What
Fix misleading comment.
```diff
- # Make sure a malicious user can obtain a session and events not belonging to them
+ # Make sure a malicious user **cannot** obtain a session or events not belonging to them
```
### Why
The previous wording contradicted the assertion `assert len(session_mismatch.events) == 0`, which verifies that a malicious user **cannot** access another user’s session or events.
### Testing plan
Docs-only change.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1959 from mthorme:fix-comment-session-mismatch b1f139af340bd240d40ed58f5dea3274c3a3bd83
PiperOrigin-RevId: 785908548
This change takes cares of SQL results containing values that are not json serializable (e.g. datetime, bignumeric) by converting them to their string representation.
PiperOrigin-RevId: 785719997
We update both adk web run eval endpoint and adk eval cli to use the LocalService. The old method is marked as deprecated and will be removed in later PRs.
PiperOrigin-RevId: 785612708
Fixes#423
Related to #1670
- This avoids the `GeneratorExit` error thrown, which would crash OTel metric collection and cause `Failed to detach context` error.
- This also allows all function calls are processed when exit_loop is called together with other tools in the same LLmResponse.
A sample agent for testing:
```
from google.adk import Agent
from google.adk.agents.loop_agent import LoopAgent
from google.adk.tools.exit_loop_tool import exit_loop
worker_1 = Agent(
name='worker_1',
description='Worker 1',
instruction="""\
Just say job #1 is done.
If job #1 is said to be done. Call exit_loop tool.""",
tools=[exit_loop],
)
worker_2 = Agent(
name='worker_2',
description='Worker 2',
instruction="""\
Just say job #2 is done.
If job #2 is said to be done. Call exit_loop tool.""",
tools=[exit_loop],
)
work_agent = LoopAgent(
name='work_agent',
description='Do all work.',
sub_agents=[worker_1, worker_2],
max_iterations=5,
)
root_agent = Agent(
model='gemini-2.0-flash',
name='hello_world_agent',
description='hello world agent that can roll a check prime',
instruction="""Hand off works to sub agents.""",
sub_agents=[work_agent],
)
```
PiperOrigin-RevId: 785538101
Merge https://github.com/google/adk-python/pull/1195
## Summary
Updated the Toolbox Agent documentation to address a critical missing dependency that prevents the agent from running successfully.
## Changes Made
- **Added missing dependency**: Documented that `toolbox-core` must be installed via `pip install toolbox-core`
- **Improved documentation structure**: Added clear section numbering and better organization
- **Enhanced readability**: Fixed grammar, capitalization, and formatting throughout
- **Added Prerequisites section**: Set clear expectations before installation begins
- **Clarified optional steps**: Made it clearer when database creation can be skipped
## Problem Solved
The original documentation was missing a crucial step - installing the `toolbox-core` package. Without this dependency, users encounter an `ImportError: No module named 'toolbox-core'` when trying to use the `ToolboxToolset` class in ADK. This fix ensures users can successfully set up and run the agent without encountering import errors.
## Testing
- Verified the installation steps work correctly with the added dependency
- Confirmed the agent runs successfully after following the updated documentation
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1195 from designcomputer:patch-1 b90c71fe95aa09a3dca069e91f14791f557ab2e3
PiperOrigin-RevId: 785487495
Merge https://github.com/google/adk-python/pull/1130
This enables the use of the `model-optimizer-*` family of models in vertex, as per the [documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/vertex-ai-model-optimizer#using-vertex-ai-model-optimizer).
To use this, ensure your location is set to `global` and pass a model optimizer model to an agent:
```python
root_agent = Agent(
model="model-optimizer-exp-04-09",
name="fast_and_slow_agent",
instruction="Answer any question the user gives you - easy or hard.",
generate_content_config=types.GenerateContentConfig(
temperature=0.01,
model_selection_config=ModelSelectionConfig(
feature_selection_preference=FeatureSelectionPreference.BALANCED
# Options: PRIORITIZE_QUALITY, BALANCED, PRIORITIZE_COST
)
),
)
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1130 from calvingiles:feat-model-optimizer 1a76bfa22420edb07d83415dcea6dd0114084e8e
PiperOrigin-RevId: 784921913
Now the LangchainTool can wrap:
* Langchain StructuredTool (sync and async).
* Langchain @Tool (sync and async).
This enhance the flexibility for user and enables async functionalities.
PiperOrigin-RevId: 784728061
**Highlights:**
- **Callback Chaining:** Now supports a list of before and after callbacks, as in the non-live version. Callbacks are executed in order, stopping when one returns a response.
- **Unit Tests:** Added new unit tests for before and after callbacks, async and sync versions, callback chains and mixed callbacks.
- **Sample Agent:** Introduced a new example agent with multiple callbacks showing various behaviors: audit, security, validation, and enhancement. This provides practical usage examples.
PiperOrigin-RevId: 783884562
This change adds activity start and end signals to the LiveRequestQueue,
allowing clients to manually control the start and end of user input in
streaming sessions when automatic voice activity detection is disabled.
The LiveRequestQueue allows users to send messages to the model with the following semantics:
- `content`: sends turn-by-turn content.
- `blob`: sends a media blob for realtime streaming (e.g., audio).
- `activity_start`: indicates the beginning of an activity.
- `activity_end`: indicates the end of an activity.
- `close`: closes the connection.
GeminiLLMConnection has been updated to send the new activity signals to the backend.
This change is a necessary to support clients (e.g. voice assistants) that do not want to use automatic voice activity detection. In this case, the client will be responsible to send the `activity_start` signal when the user starts talking, and `activity_end` when the user finishes talking.
To test the change:
run_config = RunConfig(
realtime_input_config=types.RealtimeInputConfig(
automatic_activity_detection=types.AutomaticActivityDetection(
disabled=True,
),
)
)
import threading # Add this import
def thread_target():
# Define the async operations to run in the background.
async def background_task():
live_request_queue.send_activity_start()
# live_request_queue.send_content(
# content=types.Content(
# role='user',
# parts=[types.Part.from_text(text="hi, what's the time?")],
# )
# )
await asyncio.sleep(3)
live_request_queue.send_activity_end()
PiperOrigin-RevId: 783882447
1. credential service may be accessed by callbacks
2. plan to add load_credential and save_credential method in CallbackContext (see cl/782158513) given customer has requirement to access credential service themselves. (see https://github.com/google/adk-python/issues/1816)
It's backward compatible given CallbackContext is parent class of ToolContext
PiperOrigin-RevId: 783480378
This is to support model path like :
projects/265104255505/locations/us-central1/publishers/google/models/gemini-2.0-flash-001"
PiperOrigin-RevId: 783413351
This version of the EvalSetsManager is intended to support two main behaviors
1) The agent developer wants to bring in their own eval set file, which is usually the case with `adk eval` cli. Once their eval sets are uploaded into this version of the eval sets manager, the EvalSetManager could be handed over to the Eval system for running evals.
2) As a part of AgentEvaluator testing, we expect developers to supply Eval cases in json files. The in-memory version of the EvalSetsManager will help us run those test cases using LocalEvalService.
PiperOrigin-RevId: 783198788
When get session is being called on a session with more than 1 page of events (100+), the response of the subsequent listevents calls fails due to missing parsing logic. This change fixes the processing of the listevents responses.
PiperOrigin-RevId: 783166959
1) raise explicit error if the response event contains responses against multiple function call events
2) merge all function responses for the corresponding function call event
PiperOrigin-RevId: 782154577
According to a2a protocol task artifact is a different concept from adk artifact.
if a task is completed the final result should be in task artifact.
PiperOrigin-RevId: 782154265
This change:
- Introduces the LocalEvalService Class.
- Implements only the "perform_inference" method. Evaluate method will be implemented in the next CL.
- Adds required test coverage.
PiperOrigin-RevId: 781781954
This change integrates the plugin system with ADK. PluginManager is attached to the invocation context similar to session/artifact/memory.
It includes integrations with following ADK internal callbacks:
* App callbacks: Integrated in the BaseRunner class, in run_async and run_live
* On Message callbacks: Integrated in the BaseRunner class, triggers on run_async.
* Agent callbacks: Integrated in the BaseAgent class. Leveraging the existing *callback functions
* Model callbacks: Integrating in the base_llm_flow.
* Tool callbacks: Integrated in functions.py, wrapped around the code for agent tool_callbacks
Sample code to use plugins:
```python
# Add plugins to Runner
runner = Runner(
app_name="my-app",
agent=root_agent,
artifact_service=artifact_service,
session_service=session_service,
memory_service=memory_service,
plugins=[
MySamplePlugin(),
LoggingPlugin(),
],
)
```
PiperOrigin-RevId: 781746586
Plugin is a collection of callbacks (lifecycle hooks), including callbacks for Agent, Tools, Model and App. It helps developers to add customizations and change behaviors of their agent application easily
This is the first change that introduces only the base interfaces based on the doc.
plugins folder is generated with `create_symlink.sh plugins`
PiperOrigin-RevId: 781745044
Including basic fields in configs, the from_config() methods and the JSON schema. Other fields will be added in following PRs.
PiperOrigin-RevId: 781660569
Even though InMemoryMemoryService is intended only for testing and local development, we eliminate a potential source of bugs during prototyping by providing a thread-safe InMemoryMemoryService.
PiperOrigin-RevId: 781554006
- Allow run_async to break on partial events instead of raising ValueError
- Generate aggregated streaming content regardless of finish_reason
- Add error_code and error_message to final streaming responses if model response is interrupted.
PiperOrigin-RevId: 781377328
This commit includes a number of new tests for live streaming with function calls. These tests cover various scenarios:
- Single function calls
- Multiple function calls
- Parallel function calls
- Function calls with errors
- Synchronous function calls
- Simple streaming tools
- Video streaming tools
- Stopping a streaming tool
- Multiple streaming tools simultaneously
The tests use mock models and custom runners to simulate the interaction between the agent, model, and tools. They verify that function calls are correctly generated, executed, and that the expected data is returned.
PiperOrigin-RevId: 781318483
This would allow users to easily make a copy of the agents they built without having to add too much boilerplates. This promotes code reuse, modularity and testability of agents.
PiperOrigin-RevId: 781214379
This PR extends the existing Streaming tests to consider new configurations that have been added, including:
- `output_audio_transcription`
- `input_audio_transcription`
- `realtime_input_config`
- `enable_affective_dialog`
- `proactivity`
These configurations are tested individually and also combined, to cover all the possibilities, increasing the testing coverage and ensuring everything is working as expected.
In addition, the new configuration values are also validated to be sure they are properly initialized.
PiperOrigin-RevId: 780178334
This explains the high-level architecture and philosophy of the ADK project.
It can also be feed into LLMs for vibe-coding.
PiperOrigin-RevId: 780178125
fix: Use `inspect.signature()` instead of `typing.get_type_hints()` to find the LiveRequestQueue.
Motivation: `typing.get_type_hints()` may raise errors in complex scenarios where type annotation is not available.
Add live_bidi_streaming_tools_agent example to show how to use the live streaming feature.
PiperOrigin-RevId: 780160921
Adds a description for docstring and comments in the AGENTS.md and adds a section for Versioning that describes how ADK follows Semantic Versioning 2.0.0
PiperOrigin-RevId: 778667398
test: refine test_session_state in test_session_state to catch event leakage
fix: revert app name to my_app for test_session_state test
style: fix pyink style warnings
fix: add app_name to filter as per suggestion from rpedela-recurly
We add a new metric for evaluating safety of Agent's response to ADK Eval. We delegate the actual implementation to Vertex Gen AI Eval SDK, so using this metric will require GCP project.
As a part of this change, we created (refactored) a simple Facade for vertex gen ai eval sdk.
PiperOrigin-RevId: 778580406
The LLM occasionally includes an unexpected 'parameters' argument when calling tools, specifically observed with 'transfer_to_agent'. This change makes FunctionTool.run_async more robust by filtering arguments against the function signature before invocation.
This resolves issue #1637.
Update test_function_tool.py
fix typing
fix: add `from __future__ import annotations`
`grep -L` returns status 1 when there are modified files that don't have the `from __future__ import annotations` pattern. Previously if this happens, the entire GitHub action by default will stop and exit with status 1. Adding `|| true` will prevent this from happening and continue the workflow.
PiperOrigin-RevId: 778246018
Bug: When a model emits a stream of tokens, it sometimes emits a final chunk of whitespace or no content. The agent was trying to parse that content into JSON, causing a validation error.
Fix: If a model is expected to return JSON and the last streamed token is empty/whitespace, the agent will no longer try to parse it, and exit gracefully.
New unit tests confirm the scenario and the fix.
PiperOrigin-RevId: 777609415
This example include multi agents:
- Root agent.
- Sub agent for Rolling Dice.
- Sub agent for checking primes.
Added README.md to demonstrate how to use it.
PiperOrigin-RevId: 777599625
This change adds a new enum value which the agent builder can pass in the `BigQueryToolConfig` to allow limited writes to the `execute_sql` tool.
PiperOrigin-RevId: 776661744
Fixes https://github.com/google/adk-python/issues/1180
We are using `func.now()` to set the `onupdate` time for db, when SQLAlchemy generates the SQL to build the database, it actually translates `func.now()` into `NOW()` or `CURRENT_TIMESTAMP`. The value it returns depends on the database server settings. For example, if the global/default timezone for a db is set to be UTC, the update time will be set to be a UCT time; if the global time zone for a db is set to be a local time zone (e.g. America/Los_Angeles), the update time will be a local time.
Normally, the best practice is to set database server to use UTC. Applications will convert it into different time zones as needed.
For SQLite, there is no way to config the default timezone, it will just treat it as UTC. But because it is a naive datetime (with no timezone info), python will assume it is a local time and then covert it into a UTC, which is why we see the bug (e.g. we create a session at 2025-06-17 12:49:33 local time, but when we read the session, its last update time is 2025-06-17 19:49:33 local time).
The solution is converting the native datatime to be timezone aware before `.timestamp()`.
The change in this CL only affects SQLite database.
PiperOrigin-RevId: 776654443
Merge https://github.com/google/adk-python/pull/1679
Contributing doc says to do the following:
```sh
uv sync --extra test --extra eval
pytest ./tests/unittests
```
If you follow this the tests will fail:
```sh
tests/unittests/a2a/executor/test_task_result_aggregator.py:27: in <module>
from a2a.types import Message
E ModuleNotFoundError: No module named 'a2a'
```
This makes sense since the `a2a` package is not part of ADK's core dep, it is an extra:
https://github.com/google/adk-python/blob/e79651cd86ba3f0c998109f2140f1db2cab78708/pyproject.toml#L79-L83
Thus for a2a tests to pass we must include the extra in the sync command:
```sh
uv sync --extra test --extra eval --extra a2a
pytest ./tests/unittests
```
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1679 from jackwotherspoon:main c1a536780409065db817088a8d5ed5979cca8d8f
PiperOrigin-RevId: 776617515
Additionally, few other small changes.
* Updated a test fixture to support the latest eval data schema. Somehow I missed doing that previously.
* Updated the `evaluation_generator.py` to use `run_async`, instead of `run`.
* Also, raise an informed error when dependencies required eval are not installed.
* Also, changed the behavior of AgentEvaluator.evaluate method to run all the evals, instead of failing at the first eval metric failure.
PiperOrigin-RevId: 775919127
a. fix function call long running id matching logic
b. fix error code conversion logic
c. add input required and auth required status conversion logic
d. add a2a Task/Message to ADK event converter
f. set task id and context id from input argument
PiperOrigin-RevId: 775860563
This change renames the sample agent based on the Google API based tools to reflect the larger purpose and avoid confusion with the built-in BigQuery tools. In addition, it also renames the root agent in the BigQuery sample agent to "bigquery_agent"
PiperOrigin-RevId: 775655226
Merge https://github.com/google/adk-python/pull/1451
## Description
Fixes https://github.com/google/adk-python/issues/1306 by using `async for` with `await self.llm_client.acompletion()` instead of synchronous `for` loop.
## Changes
- Updated test mocks to properly handle async streaming by creating an async generator
- Ensured proper parameter handling to avoid duplicate stream parameter
## Testing Plan
- All unit tests now pass with the async streaming implementation
- Verified with `pytest tests/unittests/models/test_litellm.py` that all streaming tests pass
- Manually tested with a sample agent using LiteLLM to confirm streaming works properly
# Test Evidence:
https://youtu.be/hSp3otI79DM
Let me know if you need anything else from me for this PR
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1451 from avidelatm:fix/litellm-async-streaming d35b9dc90b2fd6fad44c3869de0fda2514e50055
PiperOrigin-RevId: 774835130
Merge https://github.com/google/adk-python/pull/1079
Fixes part of #356
Add usage attributes to span.
Note: Since the handling of GenAI event bodies in OpenTelemetry has not yet been determined, I have temporarily added only attributes related to usage.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1079 from soundTricker:feature/356-support-more-opentelemetry-semantics 99a9d0352b4bca165baa645440e39ce7199f072b
PiperOrigin-RevId: 774834279
This change accepts the `google.auth.credentials.Credentials` type for `BigQueryCredentialsConfig`, so any subclass of that, including `google.oauth2.credentials.Credentials` would work to integrate with BigQuery service. This opens up a whole range of possibilities, such as using service account credentials to deploy an agent using these tools.
PiperOrigin-RevId: 773190440
This change sets an explicit project id in the BigQuery client from the conversation context. Without this the client was trying to set a project from the environment's application default credentials and running into issues where application default credentials is not available.
PiperOrigin-RevId: 772695883
#non-breaking
The correct conversion from 25 degrees Celsius is 77 degrees Fahrenheit. The previous value of 41 was wrong.
PiperOrigin-RevId: 772528757
Context: we'd like to separate fetcher into exchanger and refresher later. This cl help to extract the common utility that will be used by both exchanger and refresher.
PiperOrigin-RevId: 772257995
set environment variable ADK_ALLOW_WIP_FEATURES=true can bypass it.
working_in_progress features are not working. ADK users are not supposed to set this environment variable.
PiperOrigin-RevId: 771333335
* modified list issues to only return unlabelled open issues
* added github workflow to run on schedule and issue open/reopen
* interactive/workflow modes
* readme document
PiperOrigin-RevId: 771152306
1. remove unnecessary cached session instance in mcp toolset
2. move session reinitialization logic from mcp tool and mcp toolset to mcp session manager
3. add lock for the code block of session creation to avoid race conditions
PiperOrigin-RevId: 770949529
1. let auth_handler.py to utilize the oauth2 credential fetcher to exchange token
2. restructure tool_auth_handler.py to support refresh token
PiperOrigin-RevId: 770901469
Merge https://github.com/google/adk-python/pull/981
issue: https://github.com/google/adk-python/issues/982
This pull request introduces a new configuration option, `realtime_input_config`, to the `RunConfig` class.
**Reason for this change:**
Currently, there is no direct way to configure real-time audio input behaviors, such as Voice Activity Detection (VAD), for live agents through the `RunConfig`. The Gemini API documentation (specifically [Configure automatic VAD](https://ai.google.dev/gemini-api/docs/live#configure-automatic-vad)) outlines parameters for VAD that users may want to customize.
This change enables users to pass these real-time input configurations, providing more granular control over the audio input for live agents.
**Changes made:**
- Added a new optional field `realtime_input_config: Optional[types.RealtimeInputConfig]` to the `RunConfig` class.
- The docstring for `realtime_input_config` has been added to explain its purpose.
**Example Usage (Conceptual):**
While the specific structure of `types.RealtimeInputConfig` would define the exact parameters, a user might configure it like this:
```python
# (Assuming types.RealtimeInputConfig and types.VadConfig are defined elsewhere)
# import your_project.types as types
run_config = RunConfig(
# ... other configurations ...
realtime_input_config=types.RealtimeInputConfig(
automatic_activity_detection =types.AutomaticActivityDetection(
# VAD specific parameters like sensitivity, endpoint_duration_millis etc.
# based on https://ai.google.dev/gemini-api/docs/live#configure-automatic-vad
)
# Potentially other real-time input settings could be added here in the future
)
)
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/981 from ammmr:patch-add-realtime-input-config b2e17fbf5742d264029ad49bf632422b5c5b1e0a
PiperOrigin-RevId: 770797640
This change introduces unit tests in which the behavior of the tool is asserted for various query types in various write modes through a mocked BigQuery client.
PiperOrigin-RevId: 770653117
This allows to protect against any write operations (e.g. update or delete a table), useful for some agents that must only be used in a read-only mode, while the user may have write permissions.
PiperOrigin-RevId: 769803741
Merge https://github.com/google/adk-python/pull/1211
### Description
When using the Google.GenAI backend (GEMINI_API), file uploads fail if the `file_data` or `inline_data` parts of the request contain a `display_name`. The Gemini API (non-Vertex) does not support this attribute, causing a `ValueError`.
This commit updates the `_preprocess_request` method in the `Gemini` class to sanitize the request. It now iterates through all content parts and sets `display_name` to `None` if the determined backend is `GEMINI_API`. This ensures compatibility, similar to the existing handling of the `labels` attribute.
Fixes#1182
### Testing Plan
**1. Unit Tests**
- Added a new parameterized test `test_preprocess_request_handles_backend_specific_fields` to `tests/unittests/models/test_google_llm.py`.
- This test verifies:
- When the backend is `GEMINI_API`, `display_name` in `file_data` and `inline_data` is correctly set to `None`.
- When the backend is `VERTEX_AI`, `display_name` remains unchanged.
- All unit tests passed successfully.
```shell
pytest ./tests/unittests/models/test_google_llm.py ░▒▓ ✔ adk-python base system 21:14:02
============================================================================================ test session starts ============================================================================================
platform darwin -- Python 3.12.10, pytest-8.3.5, pluggy-1.6.0
rootdir: /Users/leo/PycharmProjects/adk-python
configfile: pyproject.toml
plugins: anyio-4.9.0, langsmith-0.3.42, asyncio-0.26.0, mock-3.14.0, xdist-3.6.1
asyncio: mode=Mode.AUTO, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function
collected 20 items
tests/unittests/models/test_google_llm.py .................... [100%]
============================================================================================ 20 passed in 3.19s =============================================================================================
```
**2. Manual End-to-End (E2E) Test**
I manually verified the fix using `adk web`. The test was configured to use a **Google AI Studio API key**, which is the scenario where the bug occurs.
- **Before the fix:**
When uploading a file, the request failed with the error: `{"error": "display_name parameter is not supported in Gemini API."}`. This confirms the bug.
<img width="968" alt="Screenshot 2025-06-06 at 21 22 35" src="https://github.com/user-attachments/assets/f1ab2db2-d5ec-40fc-a182-9932562b21e1" />
- **After the fix:**
With the patch applied, the same file upload was processed successfully. The agent correctly analyzed the file and responded without errors.
<img width="973" alt="Screenshot 2025-06-06 at 21 23 24" src="https://github.com/user-attachments/assets/e03228f6-0b7d-4bf9-955a-ac24efb4fb72" />
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1211 from ystory:fix/display-name d3efebe74aca635a7a255063e64f07cc44016f05
PiperOrigin-RevId: 769278445
Merge https://github.com/google/adk-python/pull/1143
## Summary
Added a DeepWiki badge to the README.md file to provide users with easy access to interactive documentation that stays automatically updated.
## Changes Made
- Added DeepWiki badge to the existing badge section in README.md
- Badge links to: https://deepwiki.com/google/adk-python
## What is DeepWiki?
DeepWiki provides up-to-date documentation you can talk to, for every repository in the world. By adding this badge to our repository, we help users find and interact with documentation more easily. Users can ask questions about the codebase and get contextual answers based on the latest repository content.
The documentation is automatically updated weekly, ensuring that users always have access to the most current information about the ADK codebase, including new features, API changes, and code examples that reflect the latest development progress.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1143 from takashikik:add-deepwiki-badge d9b8bc676c9fe2e94c7b3f0ae49814452e45b5f9
PiperOrigin-RevId: 769273276
Merge https://github.com/google/adk-python/pull/1250
The `Args:` section in the docstring of the `cli_deploy_agent_engine` function was causing formatting issues in the help output, with line breaks not being rendered correctly.
This commit removes the redundant `Args:` section from the docstring. The help text for options is already comprehensively covered by the `help` attributes in the `@click.option` decorators, and `click` automatically lists the command's arguments.
This change ensures that the help output for
`adk deploy agent_engine --help` is clean, readable, and correctly formatted, relying on `click`'s standard help generation mechanisms.
After the fix:
(adk_test234) (base) hangfeilin@Hangfeis-MBP adk-python % adk deploy agent_engine --help
Usage: adk deploy agent_engine [OPTIONS] AGENT
Deploys an agent to Agent Engine.
Args: agent (str): Required. The path to the agent to be deloyed.
Example:
adk deploy agent_engine --project=[project] --region=[region] --staging_bucket=[staging_bucket] path/to/my_agent
Options:
--project TEXT Required. Google Cloud project to deploy the agent.
--region TEXT Required. Google Cloud region to deploy the agent.
--staging_bucket TEXT Required. GCS bucket for staging the deployment artifacts.
--trace_to_cloud Optional. Whether to enable Cloud Trace for Agent Engine.
--adk_app TEXT Optional. Python file for defining the ADK application (default: a file named agent_engine_app.py)
--temp_folder TEXT Optional. Temp folder for the generated Agent Engine source files. If the folder already exists, its
contents will be removed. (default: a timestamped folder in the system temp directory).
--env_file TEXT Optional. The filepath to the `.env` file for environment variables. (default: the `.env` file in
the `agent` directory, if any.)
--requirements_file TEXT Optional. The filepath to the `requirements.txt` file to use. (default: the `requirements.txt` file
in the `agent` directory, if any.)
--help Show this message and exit.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1250 from google:fix-1191-agent-engine-help d2d0e89ed1af6ace11abe4e3bed89335dbcf9be5
PiperOrigin-RevId: 769182740
Partial fix for https://github.com/google/adk-python/issues/1170
TODOs:
- UI rendering still has issue to match the event with the correct agent.
- graph building needs further fix when there is a workflow agent in the tree.
PiperOrigin-RevId: 767711701
Even though litellm type definitions and openai API specifies content as list of dictionaries (with type and relevant attributes potentially to allow multimodal inputs/outputs in addition to text), ollama has been demonstrating marshal errors. As a workaround this change simplifies the content as string when there is no more than one content part.
Fixes#642, #928, #376
PiperOrigin-RevId: 766890141
Three fixes:
1. used "fetch-depth: 2" to ensure that files in all commits in the PR are checked
2. triggered by all changed ".py" files in the repo
3. merged the "check modified files" and "run Pyink" steps because $GITHUB_ENV cannot handle multi-line env vars without special treatment
PiperOrigin-RevId: 766793736
Merge https://github.com/google/adk-python/pull/482
Added new agent visualzation that accounts for the internal architecture of the Workflow Agents and shows them inside of a cluster with a label as the name of the Workflow Agent. The sub agents are conencted as per the Workflow Agents' working and architecture
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/482 from BhadrakshB:new_agent_visualization 994a9e28039b62d9d1d99fc73374a3fa97807aca
PiperOrigin-RevId: 766345311
This is in response to the litellm v1.71.2 + ollama v0.9.0 sending function call chunks with 0 indices across multiple calls and lacking call ids.
Solutions introduced:
1. increment fallback index when accumulated arg becomes json parsable.
2. tolerate finish reason == stop when tool calls are present
3. fallback to index when tool call id is None
Fixes https://github.com/google/adk-python/issues/294
PiperOrigin-RevId: 766258344
--
618add7d297cbe26f26f45aa01b39c3d086a13e8 by Hangfei Lin <hangfei@google.com>:
doc: Create readme.md
--
5ba85d653cac11b2858ee5d53d175c1c16d933ec by Hangfei Lin <hangfei@google.com>:
doc: Update CONTRIBUTING.md
--
02606a34babba6a660886a073332979fb2b12fc3 by Wei Sun (Jack) <weisun@google.com>:
Rename readme.md to README.md
--
08a38bd5727bf554f6fb043c73623d367e9b138e by Hangfei Lin <hangfei@google.com>:
Update README.md
--
92e7ee6d498dfce35f1c6df44c1ec0f86ae5d513 by Wei Sun (Jack) <weisun@google.com>:
Update README.md
--
69c3a44e6946b3541746ded43dae8a70d47d538f by Wei Sun (Jack) <weisun@google.com>:
Update README.md
--
9de40783990ae9935463b37225c186e91c93025d by Wei Sun (Jack) <weisun@google.com>:
Update README.md
--
0f8a011ddc5b22ba8361ce7b34413a34cfcf15ba by Wei Sun (Jack) <weisun@google.com>:
Update README.md
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1058 from google:hangfei-patch-2 81eacedef69468fa554312a187880ccf4c30c559
PiperOrigin-RevId: 766234622
--
8772b3de0b2fd04f246cc90c4c8032f9dc8cfed9 by Jaeyeon Kim <anencore94@gmail.com>:
fix: update unit test code for test_connection
- Fix for Unit Test Failures
--
8e0b45c2a64994bfda6401847e485fdd9edc8306 by Jaeyeon Kim <anencore94@gmail.com>:
fix useless changes
--
54efa004fa0fc9bcf78b49061221994650e162bc by Jaeyeon Kim <anencore94@gmail.com>:
fix conflict resolve issue
--
003ed4418c73b74bfba5ff055a364b62ddc18fa7 by Wei Sun (Jack) <weisun@google.com>:
Autoformat test_connections_client.py
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/578 from anencore94:bugfix/failed_unittests ba0e1d33ad905b0b046023b685c70f4ef05e4efa
PiperOrigin-RevId: 766221165
Copybara import of the project:
--
95292471f6dba29b55a17239670cdc6cc14619b5 by Yongsul Kim <ystory84@gmail.com>:
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/936 from ystory:fix/artifact-sample-save 7b0babc53266afadb8421ccafa0f3de092eeeae5
PiperOrigin-RevId: 766220649
Copybara import of the project:
--
ffd6184d7e402b0787b0fa37fc09cd519adcc7f3 by Calvin Giles <calvin.giles@trademe.co.nz>:
fix: Call all tools in parallel calls during partial authentication
--
c71782a582ba825dbe2246cdb5be3f273ca90dca by seanzhou1023 <seanzhou1023@gmail.com>:
Update auth_preprocessor.py
--
843af6b1bc0bc6291cb9cb23acf11840098ba6dd by seanzhou1023 <seanzhou1023@gmail.com>:
Update test_functions_request_euc.py
--
955e3fa852420ecbf196583caa3cf86b7b80ab56 by seanzhou1023 <seanzhou1023@gmail.com>:
Update test_functions_request_euc.py
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/853 from calvingiles:fix-parallel-auth-tool-calls f44671e37b9fe44a25c9b1c0c25a26fc634b011c
PiperOrigin-RevId: 765639904
Copybara import of the project:
--
6596c477c7138df79d77e67181fd5979fd1a72e3 by Garrett Bischof <bischofgarrett@gmail.com>:
docs: change eval_dataset to eval_dataset_file_path_or_dir
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/397 from gwbischof:eval_dataset e8a0d0911c21ac76dab83e8520aaebc38d24adf5
PiperOrigin-RevId: 765638775
Copybara import of the project:
--
8540f266ebc0210749834d73ee61f01783ae3526 by Edward Funnekotter (aider) <efunneko@gmail.com>:
fix: ensure function description is copied when ignoring parameters
--
b9fb5916593fe552a7b02bff379ebf2f3b3cf69f by Edward Funnekotter <efunneko@gmail.com>:
Fix annoying comments
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/552 from efunneko:efunneko/122/copy_doc_string_for_tool d9bc24343d9f32376b5647c4309d6cb172833534
PiperOrigin-RevId: 765470363
Right now the agent builder has to specify the bigquery scope explicitly for bigquery tools, which is somewhat unnecessary. With this change the user does not have to specify scopes, although they would still have the ability to overrides scopes if necessary.
PiperOrigin-RevId: 765354010
Copybara import of the project:
--
db506da1c38f0a27df51b0e672ef78d62077af78 by Cristopher Hugo Olivares Del Real <crissins041196@gmail.com>:
fix: typos in documentation
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/840 from crissins:main 76a5e9bfbe73e7744b144010741a4e80425282a9
PiperOrigin-RevId: 765347788
--
8baeb0b569eaedc638b20e46894178a3b878dbd6 by Amulya Bhatia <amulya.bhatia@t-online.de>:
test: unit tests for built_in_code_executor and unsafe_code_executor
--
cfac73b9271557ead96eb5fb419e05d88c6e8cd4 by Amulya Bhatia <amulya.bhatia@t-online.de>:
test: unit tests for built_in_code_executor and unsafe_code_executor
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/971 from iamulya:code-executor-tests 55290e27b5e58ef3835905aec88639e936318d01
PiperOrigin-RevId: 764976316
--
d9b0a6f822f773a61bcc507d252ca46da660b70b by Eugen-Bleck <eugenbleck@gmail.com>:
fix: match arg case in errors
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/724 from bl3ck:fix/preserve-arg-case-in-errors 3ac43ef2090f5e4b4158ea97cbcf16399aabe2e5
PiperOrigin-RevId: 764953570
Copybara import of the project:
--
e246af5965dfd4d032e0a3ce29513f3e2e874f73 by Alankrit Verma <alankrit386@gmail.com>:
tools: allow transfer_to_agent to accept extra kwargs
transfer_to_agent now takes **kwargs to swallow unexpected keyword args
Added integration tests covering single and multiple extra kwargs.
Fixes#458.
--
55fea786a9b7eb19b830dc67d7a2e37fe7937608 by Alankrit Verma <alankrit386@gmail.com>:
fix(tests): correct indentation in test_transfer.py for better readability
--
0c04f2d777bd4f3d8951dadd5e4e105530bd6281 by Alankrit Verma <alankrit386@gmail.com>:
fix(transfer_to_agent): restore strict two-arg signature and clarify usage
Revert the earlier **kwargs change so transfer_to_agent again only accepts
(agent_name, tool_context). Improve the doc-string to make clear that no
other parameters should be passed to this tool.
Fixes#458
--
d37448dd0ef9fc6199ca0e42b211b3cd9c886eb0 by Alankrit Verma <alankrit386@gmail.com>:
fix(transfer_to_agent): update docstring for clarity and accuracy
--
ea827af78fc2c9abdf030ad50e24bba8c996df75 by Wei Sun (Jack) <Jacksunwei@gmail.com>:
Update transfer_to_agent_tool docstring for better prompt
--
a144069a67b2e5652ffd50224b1ce68ddea14783 by Wei Sun (Jack) <Jacksunwei@gmail.com>:
Update transfer_to_agent_tool.py
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/466 from AlankritVerma01:tools/transfer-accept-kwargs 686d436457e3141d128c6e81452fddc546a14a7e
PiperOrigin-RevId: 764940463
--
cd9130aca29b5d07b069cfc4a9aa022455e005e9 by Yongsul Kim <ystory84@gmail.com>:
docs: Fix broken link to A2A example
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1021 from ystory:patch-1 5d827f7834ca33120bd2a87d63e29ac5b93eb7c9
PiperOrigin-RevId: 764937930
--
cef3ca1ed3493eebaeab3e03bdf5e56b35c0b8ef by Lucas Nobre <lucaas.sn@gmail.com>:
feat: Add index tracking to handle parallel tool call using litellm
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/759 from lucasnobre212:fix/issue_484 65e22934bf839f9ea03963b9ec6c23fdce03f59f
PiperOrigin-RevId: 764902433
Copybara import of the project:
--
c62a0a6da4317497b991f83d4d8561bdbe7292aa by Jacky W <wjx_colstu@hotmail.com>:
--
59c0606ac08ddb45ce469a4d1e1c6e515ef94df4 by Jacky W <wjx_colstu@hotmail.com>:
fix: add cache_ok option to remove sa warning.
--
1922599075af935a63544762765d6f0e6224907a by Jacky W <wjx_colstu@hotmail.com>:
chore: format code.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/1001 from Colstuwjx:fix/issue-480-precise-mysql-timestamp 50e764fb9646e326ad0204ff7adb2a5b65bf875a
PiperOrigin-RevId: 764853016
Previously if you add `from __future__ import annotations` in your code, the parsing code would fail because the type hints will be a string instead of the class itself (e.g. input: 'str' instead of input: str).
Also added "_" to the util file name.
PiperOrigin-RevId: 764817339
Copybara import of the project:
--
f56fd74efecc2cf6fbe6db70e91dfa7780fb9c68 by Mohammad <mohammaddevgermany@gmail.com>:
build(package): add py.typed and include it in flit config
This adds a py.typed marker file to the google.adk package and updates
the Flit configuration in pyproject.toml to include it in the distribution.
This ensures the package is PEP 561 compliant and allows static type
checkers (like mypy and pyright) to recognize that the package supports type hints.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/913 from mohamadghaffari:add-py-typed f56fd74efecc2cf6fbe6db70e91dfa7780fb9c68
PiperOrigin-RevId: 764603119
Copybara import of the project:
--
79962881ca1c17eb6d7bd9dcf31a44df93c9badd by Almas Akchabayev <almas.akchabayev@gmail.com>:
fix: separate thinking from text parts in streaming mode
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/777 from almeynman:separate-thinking-and-text-parts-in-stream-mode b63dcc7fd0fc3973888dcbb9d4cc7e7e0a66e7f7
PiperOrigin-RevId: 764561932
When the user id contains special characters (i.e. an email), we have added in extra url parsing to address those characters. We have also added an if statement to use the correct url when there is no user_id supplied.
Copybara import of the project:
--
ef8499001afaea40bd037c4e9946b883e23a5854 by Danny Park <dpark@calicolabs.com>:
--
773cd2b50d15b9b056b47b6155df492b0ca8034c by Danny Park <dpark@calicolabs.com>:
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/996 from dpark27:fix/list_vertex_ai_sessions d351d7f6017c03165129adc7d0212f21d1340d88
PiperOrigin-RevId: 764522026
Copybara import of the project:
--
824b4379d59a375191f8ce10997efd4021d5d0b3 by Andres Videla <andres.videla@trademe.co.nz>:
Adding regex for claude-4 models to anthropic_llm and updating tests
--
8fa2a2df1931026dc803eee0e9b60e82e90c9efa by Wei Sun (Jack) <Jacksunwei@gmail.com>:
Adds trailing comma.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/934 from avidelatm:feature/add-support-for-claude-4-models-to-anthropic_llm 8d10bacdbec952ec9832180ac6c1d220916641da
PiperOrigin-RevId: 764396694
--
50b09bbe9735c889a9c815eddcee6715ebe848da by Yuan Chai <350365422@qq.com>:
fix: improve json serialization by allowing non-ascii characters
--
c66977ae6ec4edc71a2d633eb09918eb2a226461 by Yuan Chai <350365422@qq.com>:
fix: serialize function call arguments to JSON string
Previously accepted JSON objects directly, which was less robust. Now serialize arguments to JSON strings using `_safe_json_serialize`, ensuring stability and handling non-ASCII characters correctly.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/605 from nauyiahc:fix_non_ascii_char a52513c5747296b717acee989684324e1b072d34
PiperOrigin-RevId: 764396496
Copybara import of the project:
--
bbd21e72e46227d5bbcaef6601f4a81724e7829f by Sanchit Rk <sanchitrrk@gmail.com>:
Fix: add missing kwargs to db session service
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/946 from sanchitrk:fix/missing-kwargs-db-session-service ebb699b04d8420ad14244cf3d43a2982b01d6b7f
PiperOrigin-RevId: 764392251
Copybara import of the project:
--
a6e3a220a507a27523e427e88a803f4fec40db9c by Alankrit Verma <alankrit386@gmail.com>:
test(base_llm_flow): add test for infinite loop on truncated responses
--
b5f2245788b8ed51189d1ad057372989452f070d by Alankrit Verma <alankrit386@gmail.com>:
feat(base_llm_flow): break run_async loop on partial/truncated events
--
cbbae4c468a4de3b5a737aef07cb4615f8418c38 by Wei Sun (Jack) <Jacksunwei@gmail.com>:
Raise ValueError if the last event is partial.
This is invalid state for llm flow.
--
6eebae0bc27c664eee4743ff7278ae5803415c9f by Wei Sun (Jack) <Jacksunwei@gmail.com>:
Delete tests/unittests/flows/llm_flows/test_base_llm_flow_truncation.py
--
e08b0ab19ca6eb88eb84f044bf72e815b2cf317c by Wei Sun (Jack) <Jacksunwei@gmail.com>:
format base_llm_flow.py
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/659 from AlankritVerma01:fix/522-base-llm-flow-truncation e08b0ab19ca6eb88eb84f044bf72e815b2cf317c
PiperOrigin-RevId: 764380150
Structures supported:
a) agents_dir/agent_name.py (with root_agent or agent.root_agent in it)
b) agents_dir/agent_name_folder/__init__.py (with root_agent or agent.root_agent in the package)
c) agents_dir/agent_name_folder/agent.py (where agent.py has root_agent)
PiperOrigin-RevId: 763943716
This was introduced to work around google-auth kills all logs via `google` root logging namespace. Given we're now using `google_adk` as root logging namesapce, we don't need additional Stream log handler now.
PiperOrigin-RevId: 763924531
--
b781880d9bfb9786bd5e50314eaedc441fc2a93e by Stephen Smith <stephen.smith@newfront.com>:
Telemetry unit test for non-serializable data.
--
179da9db997bb3f992e126c9c64193ff7df67b3d by Stephen Smith <stephen.smith@newfront.com>:
When converting the llm_request to JSON, skip non-serializable data.
--
5dc68f4f5a6d12b753fdb81d1449716d13490afb by Stephen Smith <stephen.smith@newfront.com>:
Update _create_invocation_context() return type to InvocationContext.
--
23a33f754409fcd2a7641098d68cef7e4f1c72c6 by Stephen Smith <stephen.smith@newfront.com>:
Oops, remove unnecessary import.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/879 from stephensmithnewfront:main f71e195a9ed157e4c0b3abfa74ae078b0c1a920a
PiperOrigin-RevId: 763922003
Copybara import of the project:
--
d01a8fd5f079bc4fca9e4b71796dbe65312ce9ff by Leo Yongsul Kim <ystory84@gmail.com>:
fix(DatabaseSessionService): Align event filtering and ordering logic
This commit addresses inconsistencies in how DatabaseSessionService
handles config.after_timestamp and config.num_recent_events
parameters, aligning its behavior with InMemorySessionService and
VertexAiSessionService.
Key changes:
- Made after_timestamp filtering inclusive
- Corrected num_recent_events behavior to fetch the N most recent events
- Refined timezone handling for after_timestamp
- Updated the unit test test_get_session_with_config to includeSessionServiceType.DATABASE, allowing verification of these fixes.
Fixes#911
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/915 from ystory:fix/database-session-timestamp-recency 5cc8cf5f5a5c0cb3e87f6ab178a5725d3f696c88
PiperOrigin-RevId: 763874840
--
73826d258b136f92a8da8171f7dc14d5f07de8dd by Calvin Giles <calvin.giles@trademe.co.nz>:
fix: Enable InMemoryRunner to be used in async tests
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/868 from calvingiles:enable-test-runner-in-async fb9033ed6f350a3114859715cae51798f864ecf6
PiperOrigin-RevId: 763233472
--
76f579c8f75e28c79e322dc60c9dca56ac96d0fa by Hangfei Lin <hangfei@google.com>:
doc: Update README.md
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/901 from google:hangfei-patch-3 6c5e264c8134e8eb164114992f3d8f2f2efe83fc
PiperOrigin-RevId: 762603928
--
aa92081193ccf4710e5aefb93c715791eab2c2ef by Stephen Smith <stephen.smith@newfront.com>:
docs: Fix typos in issue templates.
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/880 from stephensmithnewfront:stephensmithnewfront/address-typos-in-issue-templates-pr 65b7f85e26fca76b3e076ef0b826189353e8ab13
PiperOrigin-RevId: 762259304
--
004eb36c16b042ba2d8be0cca39b739c0c8ca6c1 by sudu <teric@outlook.com>:
Update tools.yaml
When search hotels with some LLM, the date format shows as bellow
```
**Check-in Date:** April 23, 2024
```
So i update the SQL in tools.yaml to be compatible with following instruction:
```sql
update checkin date to 'April 24,2024' and checkout date to 'April 26,2024' of Best Western Bern
```
--
1300688ee1407212658d57712c1ad6ee61b052fe by qidu <qidu@outlook.com>:
Fix the tools of `ToolboxToolset` initialization bugs for
`samples/toolbox_agent`
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/794 from qidu:main 5b3199da564efdd07915e24e75659055a17dad82
PiperOrigin-RevId: 762259287
--
cd8c580cbd4a2dc1c49c690ea81c4111860aa52c by Hangfei Lin <hangfei@google.com>:
doc: Update README.md
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/842 from google:hangfei-patch-2 aa9842a43d8c464a8999beb2f6f5d491aa63ef6c
PiperOrigin-RevId: 761722188
This is useful for injecting artifacts and session state variable into instruction template typically in instruction providers.
PiperOrigin-RevId: 761595473
Copybara import of the project:
--
9e51865a6dd4de4d20088e8a7ac9f3a75501aa6b by Amulya Bhatia <amulya.bhatia@t-online.de>:
test: unit tests for code_executor_context.py
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/780 from iamulya:test-code-executor-context 907b1712e43b8ce90cd8786780bef863adfcc167
PiperOrigin-RevId: 761294975
echo "❌ Do not import from the cli package outside of the cli package. If you need to reuse the code elsewhere, please move the code outside of the cli package."
echo "The following files contain the forbidden pattern:"
echo "$FILES_WITH_FORBIDDEN_IMPORT"
exit 1
else
echo "✅ No instances of importing from the cli package found in relevant changed Python files."
This document provides context for the Gemini CLI and Gemini Code Assist to understand the project and assist with development.
## Project Overview
The Agent Development Kit (ADK) is an open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control. While optimized for Gemini and the Google ecosystem, ADK is model-agnostic, deployment-agnostic, and is built for compatibility with other frameworks. ADK was designed to make agent development feel more like software development, to make it easier for developers to create, deploy, and orchestrate agentic architectures that range from simple tasks to complex workflows.
## Project Architecture
Please refer to [ADK Project Overview and Architecture](https://github.com/google/adk-python/blob/main/contributing/adk_project_overview_and_architecture.md) for details.
### ADK Live (Bidi-streaming)
- ADK live feature can be accessed from runner.run_live(...) and corresponding FAST api endpoint.
- ADK live feature is built on top of [Gemini Live API](https://cloud.google.com/vertex-ai/generative-ai/docs/live-api). We integrate Gemini Live API through [GenAI SDK](https://github.com/googleapis/python-genai).
- ADK live related configs are in [run_config.py](https://github.com/google/adk-python/blob/main/src/google/adk/agents/run_config.py).
- ADK live under multi-agent scenario: we convert the audio into text. This text will be passed to next agent as context.
- Most logics are in [base_llm_flow.py](https://github.com/google/adk-python/blob/main/src/google/adk/flows/llm_flows/base_llm_flow.py) and [gemini_llm_connection.py](https://github.com/google/adk-python/blob/main/src/google/adk/models/gemini_llm_connection.py).
- Input transcription and output transcription should be added to session as Event.
- User audio or model audio should be saved into artifacts with a reference in Event to it.
- Tests are in [tests/unittests/streaming](https://github.com/google/adk-python/tree/main/tests/unittests/streaming).
## ADK: Style Guides
### Python Style Guide
The project follows the Google Python Style Guide. Key conventions are enforced using `pylint` with the provided `pylintrc` configuration file. Here are some of the key style points:
***Indentation**: 2 spaces.
***Line Length**: Maximum 80 characters.
***Naming Conventions**:
*`function_and_variable_names`: `snake_case`
*`ClassNames`: `CamelCase`
*`CONSTANTS`: `UPPERCASE_SNAKE_CASE`
***Docstrings**: Required for all public modules, functions, classes, and methods.
***Imports**: Organized and sorted.
***Error Handling**: Specific exceptions should be caught, not general ones like `Exception`.
### Autoformat
We have autoformat.sh to help solve import organize and formatting issues.
```bash
# Run in open_source_workspace/
$ ./autoformat.sh
```
### In ADK source
Below styles applies to the ADK source code (under `src/` folder of the Github.
repo).
#### Use relative imports
```python
# DO
from..agents.llm_agentimportLlmAgent
# DON'T
fromgoogle.adk.agents.llm_agentimportLlmAgent
```
#### Import from module, not from `__init__.py`
```python
# DO
from..agents.llm_agentimportLlmAgent
# DON'T
from..agentsimportLlmAgent# import from agents/__init__.py
```
#### Always do `from __future__ import annotations`
```python
# DO THIS, right after the open-source header.
from__future__importannotations
```
Like below:
```python
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from__future__importannotations
# ... the rest of the file.
```
This allows us to forward-reference a class without quotes.
Check out go/pep563 for details.
### In ADK tests
#### Use absolute imports
In tests, we use `google.adk` same as how our users uses.
```python
# DO
fromgoogle.adk.agents.llm_agentimportLlmAgent
# DON'T
from..agents.llm_agentimportLlmAgent
```
## ADK: Local testing
### Unit tests
Run below command:
```bash
$ pytest tests/unittests
```
## Docstring and comments
### Comments - Explaining the Why, Not the What
Philosophy: Well-written code should be largely self-documenting. Comments
serve a different purpose: they should explain the complex algorithms,
non-obvious business logic, or the rationale behind a particular implementation
choice—the things the code cannot express on its own. Avoid comments that
merely restate what the code does (e.g., # increment i above i += 1).
Style: Comments should be written as complete sentences. Block comments must
begin with a # followed by a single space.
## Versioning
ADK adherence to Semantic Versioning 2.0.0
Core Principle: The adk-python project strictly adheres to the Semantic
Versioning 2.0.0 specification. All release versions will follow the
MAJOR.MINOR.PATCH format.
### Breaking Change
A breaking change is any modification that introduces backward-incompatible
changes to the public API. In the context of the ADK, this means a change that
could force a developer using the framework to alter their existing code to
upgrade to the new version. The public API is not limited to just the Python
function and class signatures; it also encompasses data schemas for stored
information (like evaluation datasets), the command-line interface (CLI),
and the data format used for server communications.
### Public API Surface Definition
The "public API" of ADK is a broad contract that extends beyond its Python
function signatures. A breaking change in any of the following areas can
disrupt user workflows and the wider ecosystem of agents and tools built with
ADK. The analysis of the breaking changes introduced in v1.0.0 demonstrates the
expansive nature of this contract. For the purposes of versioning, the ADK
Public API Surface is defined as:
- All public classes, methods, and functions in the google.adk namespace.
- The names, required parameters, and expected behavior of all built-in Tools
(e.g., google_search, BuiltInCodeExecutor).
- The structure and schema of persisted data, including Session data, Memory,
and Evaluation datasets.
- The JSON request/response format of the ADK API server(FastAPI server)
used by adk web, including field casing conventions.
- The command-line interface (CLI) commands, arguments, and flags (e.g., adk deploy).
- The expected file structure for agent definitions that are loaded by the
framework (e.g., the agent.py convention).
#### Checklist for Breaking Changes:
The following changes are considered breaking and necessitate a MAJOR version
bump.
- API Signature Change: Renaming, removing, or altering the required parameters
of any public class, method, or function (e.g., the removal of the list_events
method from BaseSessionService).
- Architectural Shift: A fundamental change to a core component's behavior
(e.g., making all service methods async, which requires consumers to use await).
- Data Schema Change: A non-additive change to a persisted data schema that
renders old data unreadable or invalid (e.g., the redesign of the
MemoryService and evaluation dataset schemas).
- Tool Interface Change: Renaming a built-in tool, changing its required
parameters, or altering its fundamental purpose (e.g., replacing
BuiltInCodeExecutionTool with BuiltInCodeExecutor and moving it from the tools
parameter to the code_executor parameter of an Agent).
- Configuration Change: Altering the required structure of configuration files
or agent definition files that the framework loads (e.g., the simplification
of the agent.py structure for MCPToolset).
- Wire Format Change: Modifying the data format for API server interactions
(e.g., the switch from snake_case to camelCase for all JSON payloads).
- Dependency Removal: Removing support for a previously integrated third-party
library or tool type.
## Commit Message Format
- Please use [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/)
format.
- If it's not a breaking change, please add #non-breaking tag. If it's a
[Google's Open Source Community Guidelines](https://opensource.google/conduct/).
## Contribution workflow
### Finding Issues to Work On
- Browse issues labeled **`good first issue`** (newcomer-friendly) or **`help wanted`** (general contributions).
- For other issues, please kindly ask before contributing to avoid duplication.
### Requirement for PRs
- All PRs, other than small documentation or typo fixes, should have a Issue assoicated. If not, please create one.
- Small, focused PRs. Keep changes minimal—one concern per PR.
- For bug fixes or features, please provide logs or screenshot after the fix is applied to help reviewers better understand the fix.
- Please include a `testing plan` section in your PR to talk about how you will test. This will save time for PR review. See `Testing Requirements` section for more details.
### Large or Complex Changes
For substantial features or architectural revisions:
- Open an Issue First: Outline your proposal, including design considerations and impact.
- Gather Feedback: Discuss with maintainers and the community to ensure alignment and avoid duplicate work
### Testing Requirements
To maintain code quality and prevent regressions, all code changes must include comprehensive tests and verifiable end-to-end (E2E) evidence.
#### Unit Tests
Please add or update unit tests for your change. Please include a summary of passed `pytest` results.
Requirements for unit tests:
- **Coverage:** Cover new features, edge cases, error conditions, and typical use cases.
- **Location:** Add or update tests under `tests/unittests/`, following existing naming conventions (e.g., `test_<module>_<feature>.py`).
- **Framework:** Use `pytest`. Tests should be:
- Fast and isolated.
- Written clearly with descriptive names.
- Free of external dependencies (use mocks or fixtures as needed).
- **Quality:** Aim for high readability and maintainability; include docstrings or comments for complex scenarios.
#### Manual End-to-End (E2E) Tests
Manual E2E tests ensure integrated flows work as intended. Your tests should cover all scenarios. Sometimes, it's also good to ensure relevant functionality is not impacted.
Depending on your change:
- **ADK Web:**
- Use the `adk web` to verify functionality.
- Capture and attach relevant screenshots demonstrating the UI/UX changes or outputs.
- Label screenshots clearly in your PR description.
- **Runner:**
- Provide the testing setup. For example, the agent definition, and the runner setup.
- Execute the `runner` tool to reproduce workflows.
- Include the command used and console output showing test results.
- Highlight sections of the log that directly relate to your change.
### Documentation
For any changes that impact user-facing documentation (guides, API reference, tutorials), please open a PR in the [adk-docs](https://github.com/google/adk-docs) repository to update relevant part before or alongside your code PR.
### Development Setup
1.**Clone the repository:**
```shell
git clone git@github.com:google/adk-python.git
cd adk-python
```
2. **Create and activate a virtual environment:**
```shell
python -m venv .venv
```
```shell
source .venv/bin/activate
```
**windows**
```shell
source .\.venv\Scripts\activate
```
3. **Install dependencies:**
```shell
pip install uv
uv sync --all-extras
```
4. **Run unit tests:**
```shell
uv run pytest ./tests/unittests
```
5. **Run pyink to format codebase:**
```shell
uv run pyink --config pyproject.toml ./src
```
6. **Build the package**
```shell
uv build
```
7. **Local Testing**
Have a simple testing folder setup as mentioned in the [quickstart](https://google.github.io/adk-docs/get-started/quickstart/)
then install the local package with changes after building it using the below command to test the changes.
[](https://github.com/google/adk-python/actions/workflows/python-unit-tests.yml)
- **Tool Confirmation**: A [tool confirmation flow(HITL)](https://google.github.io/adk-docs/tools/confirmation/) that can guard tool execution with explicit confirmation and custom input
For remote agent-to-agent communication, ADK integrates with the
[A2A protocol](https://github.com/google/A2A/).
See this [example](https://github.com/google/A2A/tree/main/samples/python/agents/google_adk)
for how they can work together.
## 🤝 Contributing
We welcome contributions from the community! Whether it's bug reports, feature requests, documentation improvements, or code contributions, please see our
- [General contribution guideline and flow](https://google.github.io/adk-docs/contributing-guide/#questions).
We welcome contributions from the community! Whether it's bug reports, feature requests, documentation improvements, or code contributions, please see our
- [General contribution guideline and flow](https://google.github.io/adk-docs/contributing-guide/).
- Then if you want to contribute code, please read [Code Contributing Guidelines](./CONTRIBUTING.md) to get started.
## Vibe Coding
If you are to develop agent via vibe coding the [llms.txt](./llms.txt) and the [llms-full.txt](./llms-full.txt) can be used as context to LLM. While the former one is a summarized one and the later one has the full information in case your LLM has big enough context window.
## 📄 License
This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details.
## Preview
This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of the [Service Specific Terms](https://cloud.google.com/terms/service-terms#1). Pre-GA features are available "as is" and might have limited support. For more information, see the [launch stage descriptions](https://cloud.google.com/products?hl=en#product-launch-stages).
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.