Skip to content

Commit 86e7664

Browse files
sarojroutcopybara-github
authored andcommitted
feat(runners): Allow app_name to override app.name when both provided
Merge #3745 This change enables Agent Engine deployments to use App objects with event compaction and context caching configs while using the Agent Engine resource name for session operations, rather than App.name. - Allow app_name parameter to override app.name when both are provided - Still error when app and agent are both provided (prevents confusion) - Updated tests to reflect new behavior and added test for override case - Updateed documentation to clarify the new usage pattern This fixes the issue where App.name (a simple identifier) conflicts with Agent Engine's requirement for resource names in session creation. Related to issue #3715 **Please ensure you have read the [contribution guide](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) before creating a pull request.** ### Link to Issue or Description of Change **1. Link to an existing issue (if applicable):** - Closes: #3715 - Related: #3715 **2. Or, if no issue exists, describe the change:** _If applicable, please follow the issue templates to provide as much detail as possible._ **Problem:** When deploying an agent to Agent Engine with event compaction and/or context caching enabled, users must wrap their agent in an `App` object to configure these features. However, when the `App` is passed to `AdkApp` and deployed, session creation fails because: 1. `App.name` is validated as a simple Python identifier (e.g., `"my_agent_name"`) via `validate_app_name()` 2. Agent Engine expects the app name to be either a full Reasoning Engine resource name (e.g., `"projects/123/locations/us-central1/reasoningEngines/456"`) or the reasoning engine ID 3. When an `App` object is passed to `AdkApp`, the deployment stores `App.name` (the simple identifier), but session creation later rejects it as invalid This prevents users from deploying to Agent Engine with event compaction or context caching enabled. **Solution:** Allow the `app_name` parameter in `Runner.__init__()` to override `app.name` when both are provided. This enables Agent Engine (and other deployment scenarios) to: - Pass the full `App` object to preserve event compaction and context caching configurations - Override `app.name` with the Agent Engine resource name for session operations - Successfully create sessions using the resource name while maintaining App-level features The change is backward compatible: existing code that only provides `app` continues to use `app.name` as before. The override only applies when `app_name` is explicitly provided along with `app`. ### Testing Plan _Please describe the tests that you ran to verify your changes. This is required for all PRs that are not small documentation or typo fixes._ **Unit Tests:** - [x] I have added or updated unit tests for my change. - [x] All unit tests pass locally. 1. **Updated existing test** (`test_runner_init_raises_error_with_app_and_agent`): - Changed from testing `app` + `app_name` + `agent` error to testing only `app` + `agent` error - Verifies that `app` and `agent` cannot both be provided (prevents confusion) 2. **Added new test** (`test_runner_init_allows_app_name_override_with_app`): - Verifies that `app_name` can override `app.name` when both are provided - Confirms that `runner.app_name == "override_name"` while `runner.app` still references the original App object - Ensures all App configs (agent, plugins, context_cache_config, etc.) are preserved ``` pytest tests/unittests/test_runners.py::TestRunnerWithPlugins::test_runner_init_raises_error_with_app_and_agent -v pytest tests/unittests/test_runners.py::TestRunnerWithPlugins::test_runner_init_allows_app_name_override_with_app -v ``` tests/unittests/test_runners.py::TestRunnerWithPlugins::test_runner_init_allows_app_name_override_with_app PASSED [100%] tests/unittests/test_runners.py::TestRunnerWithPlugins::test_runner_init_raises_error_with_app_and_agent PASSED [100%] **Manual End-to-End (E2E) Tests:** 1. Create an agent with event compaction and context caching: ```python from google.adk import Agent from google.adk.apps import App from google.adk.apps import EventsCompactionConfig from google.adk.agents import ContextCacheConfig root_agent = Agent( name="my_agent", model="gemini-2.5-flash", instruction="You are a helpful assistant.", ) app = App( name="my_agent", root_agent=root_agent, events_compaction_config=EventsCompactionConfig( compaction_interval=2, overlap_size=1, ), context_cache_config=ContextCacheConfig(), ) ``` 2. Create a Runner with app and override app_name: ```python from google.adk import Runner from google.adk.sessions import InMemorySessionService from google.adk.artifacts import InMemoryArtifactService runner = Runner( app=app, app_name="projects/123/locations/us-central1/reasoningEngines/456", # Resource name session_service=InMemorySessionService(), artifact_service=InMemoryArtifactService(), ) # Verify app_name override worked assert runner.app_name == "projects/123/locations/us-central1/reasoningEngines/456" assert runner.app == app # Original app object preserved assert runner.context_cache_config is not None # Config preserved assert runner.app.events_compaction_config is not None # Config preserved ``` 3. Verify session creation uses the overridden name: ```python session = await runner.session_service.create_session( app_name=runner.app_name, # Uses resource name, not app.name user_id="test_user", ) ``` **Expected Results:** - Runner creation succeeds with both `app` and `app_name` provided - `runner.app_name` equals the provided `app_name` (not `app.name`) - All App configurations (event compaction, context caching) are preserved - Session creation uses the overridden `app_name` ### Checklist - [x] I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document. - [x] I have performed a self-review of my own code. - [x] I have commented my code, particularly in hard-to-understand areas. - [x] I have added tests that prove my fix is effective or that my feature works. - [x] New and existing unit tests pass locally with my changes. - [x] I have manually tested my changes end-to-end. - [x] Any dependent changes have been merged and published in downstream modules. ### Additional context **Backward Compatibility:** This change is fully backward compatible. All existing code patterns continue to work: - `Runner(app=my_app)` → Still uses `app.name` - `Runner(app_name="x", agent=my_agent)` → Still works - `Runner(app=my_app, app_name=None)` → Still works (uses `app.name`) **Impact on Agent Engine:** This change enables Agent Engine deployments to support event compaction and context caching. Once this PR is merged, Agent Engine SDK should: 1. Accept `App` objects from `AdkApp(app=my_app, ...)` 2. Create `Runner` with both `app` and `app_name` (resource name): ```python runner = Runner( app=my_app, # Preserves event_compaction_config and context_cache_config app_name=resource_name, # Overrides app.name for session operations session_service=session_service, ... ) ``` 3. Event compaction and context caching will work automatically once the App is passed correctly. **Related Documentation:** - Event compaction is documented in `src/google/adk/apps/compaction.py` - Context caching is documented in `src/google/adk/agents/context_cache_config.py` - The Runner's App support is documented in `src/google/adk/runners.py` COPYBARA_INTEGRATE_REVIEW=#3745 from sarojrout:feat/agent-engine-app-name-override 22d91d5 PiperOrigin-RevId: 854325898
1 parent 0fe3870 commit 86e7664

2 files changed

Lines changed: 41 additions & 18 deletions

File tree

src/google/adk/runners.py

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -153,15 +153,21 @@ def __init__(
153153
"""Initializes the Runner.
154154
155155
Developers should provide either an `app` instance or both `app_name` and
156-
`agent`. Providing a mix of `app` and `app_name`/`agent` will result in a
157-
`ValueError`. Providing `app` is the recommended way to create a runner.
156+
`agent`. When `app` is provided, `app_name` can optionally override the
157+
app's name (useful for deployment scenarios like Agent Engine where the
158+
resource name differs from the app's identifier). However, `agent` should
159+
not be provided when `app` is provided. Providing `app` is the recommended
160+
way to create a runner.
158161
159162
Args:
160-
app: An optional `App` instance. If provided, `app_name` and `agent`
161-
should not be specified.
163+
app: An optional `App` instance. If provided, `agent` should not be
164+
specified. `app_name` can optionally override `app.name`.
162165
app_name: The application name of the runner. Required if `app` is not
163-
provided.
164-
agent: The root agent to run. Required if `app` is not provided.
166+
provided. If `app` is provided, this can optionally override `app.name`
167+
(e.g., for deployment scenarios where a resource name differs from the
168+
app identifier).
169+
agent: The root agent to run. Required if `app` is not provided. Should
170+
not be provided when `app` is provided.
165171
plugins: Deprecated. A list of plugins for the runner. Please use the
166172
`app` argument to provide plugins instead.
167173
artifact_service: The artifact service for the runner.
@@ -171,8 +177,8 @@ def __init__(
171177
plugin_close_timeout: The timeout in seconds for plugin close methods.
172178
173179
Raises:
174-
ValueError: If `app` is provided along with `app_name` or `plugins`, or
175-
if `app` is not provided but either `app_name` or `agent` is missing.
180+
ValueError: If `app` is provided along with `agent` or `plugins`, or if
181+
`app` is not provided but either `app_name` or `agent` is missing.
176182
"""
177183
self.app = app
178184
(
@@ -213,7 +219,8 @@ def _validate_runner_params(
213219
214220
Args:
215221
app: An optional `App` instance.
216-
app_name: The application name of the runner.
222+
app_name: The application name of the runner. Can override app.name when
223+
app is provided.
217224
agent: The root agent to run.
218225
plugins: A list of plugins for the runner.
219226
@@ -232,18 +239,16 @@ def _validate_runner_params(
232239
)
233240

234241
if app:
235-
if app_name:
236-
raise ValueError(
237-
'When app is provided, app_name should not be provided.'
238-
)
239242
if agent:
240243
raise ValueError('When app is provided, agent should not be provided.')
241244
if plugins:
242245
raise ValueError(
243246
'When app is provided, plugins should not be provided and should be'
244247
' provided in the app instead.'
245248
)
246-
app_name = app.name
249+
# Allow app_name to override app.name (useful for deployment scenarios
250+
# like Agent Engine where resource names differ from app identifiers)
251+
app_name = app_name or app.name
247252
agent = app.root_agent
248253
plugins = app.plugins
249254
context_cache_config = app.context_cache_config

tests/unittests/test_runners.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -648,20 +648,38 @@ async def test_runner_passes_plugin_close_timeout(self):
648648
)
649649
assert runner.plugin_manager._close_timeout == 10.0
650650

651-
def test_runner_init_raises_error_with_app_and_app_name_and_agent(self):
652-
"""Test that ValueError is raised when app, app_name and agent are provided."""
651+
@pytest.mark.filterwarnings(
652+
"ignore:The `plugins` argument is deprecated:DeprecationWarning"
653+
)
654+
def test_runner_init_raises_error_with_app_and_agent(self):
655+
"""Test that ValueError is raised when app and agent are provided."""
653656
with pytest.raises(
654657
ValueError,
655-
match="When app is provided, app_name should not be provided.",
658+
match="When app is provided, agent should not be provided.",
656659
):
657660
Runner(
658661
app=App(name="test_app", root_agent=self.root_agent),
659-
app_name="test_app",
660662
agent=self.root_agent,
661663
session_service=self.session_service,
662664
artifact_service=self.artifact_service,
663665
)
664666

667+
@pytest.mark.filterwarnings(
668+
"ignore:The `plugins` argument is deprecated:DeprecationWarning"
669+
)
670+
def test_runner_init_allows_app_name_override_with_app(self):
671+
"""Test that app_name can override app.name when both are provided."""
672+
app = App(name="test_app", root_agent=self.root_agent)
673+
runner = Runner(
674+
app=app,
675+
app_name="override_name",
676+
session_service=self.session_service,
677+
artifact_service=self.artifact_service,
678+
)
679+
assert runner.app_name == "override_name"
680+
assert runner.agent == self.root_agent
681+
assert runner.app == app
682+
665683
def test_runner_init_raises_error_without_app_and_app_name(self):
666684
"""Test ValueError is raised when app is not provided and app_name is missing."""
667685
with pytest.raises(

0 commit comments

Comments
 (0)