From 04975a78c6ba80e8cea14523f73b722ff54eec8e Mon Sep 17 00:00:00 2001 From: Sumedh Aerram Date: Thu, 26 Nov 2026 23:53:32 -0800 Subject: [PATCH] fix(runners): save input blobs as artifacts for LlmAgent roots Reuse the legacy upload handling in the node runner message path so explicitly enabled saving preserves artifact names, placeholder parts, and service versioning. Fixes #8399 --- src/google/adk/runners.py | 69 ++++++++++++++++--------- tests/unittests/test_runners.py | 91 +++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+), 24 deletions(-) diff --git a/src/google/adk/runners.py b/src/google/adk/runners.py index 6369b91b7cd..3405a647f81 100644 --- a/src/google/adk/runners.py +++ b/src/google/adk/runners.py @@ -719,6 +719,10 @@ async def _append_user_event( """Append a user message event to the session and return it.""" if content.parts and any(p.function_call for p in content.parts): raise ValueError('User message cannot contain function calls.') + if ic.run_config and ic.run_config.save_input_blobs_as_artifacts: + await self._save_input_blobs_as_artifacts( + new_message=content, invocation_context=ic, session=ic.session + ) return await self._build_and_append_user_event( ic, content=content, state_delta=state_delta ) @@ -1628,33 +1632,15 @@ async def _exec_with_plugin( for abort_event in abort_events: yield abort_event - async def _append_new_message_to_session( + async def _save_input_blobs_as_artifacts( self, *, - session: Session | None = None, new_message: types.Content, invocation_context: InvocationContext, - save_input_blobs_as_artifacts: bool = False, - state_delta: dict[str, Any] | None = None, + session: Session, ) -> None: - """Appends a new message to the session. - - Args: - session: The session to append the message to (optional, defaults to - invocation_context.session). - new_message: The new message to append. - invocation_context: The invocation context for the message. - save_input_blobs_as_artifacts: Whether to save input blobs as artifacts. - state_delta: Optional state changes to apply to the session. - """ - target_session = session or invocation_context.session - if not new_message.parts: - raise ValueError('No parts in the new_message.') - - if any(p.function_call for p in new_message.parts): - raise ValueError('User message cannot contain function calls.') - - if self.artifact_service and save_input_blobs_as_artifacts: + """Saves inline uploads using the legacy RunConfig artifact contract.""" + if self.artifact_service: # Issue deprecation warning warnings.warn( "The 'save_input_blobs_as_artifacts' parameter is deprecated. Use" @@ -1667,20 +1653,55 @@ async def _append_new_message_to_session( # The runner directly saves the artifacts (if applicable) in the # user message and replaces the artifact data with a file name # placeholder. + if not new_message.parts: + return for i, part in enumerate(new_message.parts): if part.inline_data is None: continue file_name = f'artifact_{invocation_context.invocation_id}_{i}' await self.artifact_service.save_artifact( app_name=self.app_name, - user_id=target_session.user_id, - session_id=target_session.id, + user_id=session.user_id, + session_id=session.id, filename=file_name, artifact=part, ) new_message.parts[i] = types.Part( text=f'Uploaded file: {file_name}. It is saved into artifacts' ) + + async def _append_new_message_to_session( + self, + *, + session: Session | None = None, + new_message: types.Content, + invocation_context: InvocationContext, + save_input_blobs_as_artifacts: bool = False, + state_delta: dict[str, Any] | None = None, + ) -> None: + """Appends a new message to the session. + + Args: + session: The session to append the message to (optional, defaults to + invocation_context.session). + new_message: The new message to append. + invocation_context: The invocation context for the message. + save_input_blobs_as_artifacts: Whether to save input blobs as artifacts. + state_delta: Optional state changes to apply to the session. + """ + target_session = session or invocation_context.session + if not new_message.parts: + raise ValueError('No parts in the new_message.') + + if any(p.function_call for p in new_message.parts): + raise ValueError('User message cannot contain function calls.') + + if save_input_blobs_as_artifacts: + await self._save_input_blobs_as_artifacts( + new_message=new_message, + invocation_context=invocation_context, + session=target_session, + ) # Appends only. We do not yield the event because it's not from the model. await self._build_and_append_user_event( invocation_context, diff --git a/tests/unittests/test_runners.py b/tests/unittests/test_runners.py index 4a116c7b158..2874c9ae985 100644 --- a/tests/unittests/test_runners.py +++ b/tests/unittests/test_runners.py @@ -41,6 +41,7 @@ from google.adk.agents.parallel_agent import ParallelAgent from google.adk.agents.remote_a2a_agent import RemoteA2aAgent from google.adk.agents.run_config import RunConfig +from google.adk.agents.sequential_agent import SequentialAgent from google.adk.apps.app import App from google.adk.apps.app import EventsCompactionConfig from google.adk.apps.app import ResumabilityConfig @@ -59,6 +60,7 @@ from google.adk.events.event import NodeInfo from google.adk.models.google_llm import Gemini from google.adk.plugins.base_plugin import BasePlugin +from google.adk.plugins.save_files_as_artifacts_plugin import SaveFilesAsArtifactsPlugin from google.adk.runners import Runner from google.adk.sessions.base_session_service import BaseSessionService from google.adk.sessions.base_session_service import GetSessionConfig @@ -7744,5 +7746,94 @@ async def _consume(): assert not [e for e in session.events if e.actions.compaction] +@pytest.mark.parametrize("root_kind", ["llm", "workflow", "composite"]) +@pytest.mark.parametrize("save_blobs", [True, False, None]) +@pytest.mark.parametrize("use_plugin", [False, True]) +@pytest.mark.parametrize("has_artifact_service", [False, True]) +async def test_run_async_input_blob_artifacts( + root_kind, save_blobs, use_plugin, has_artifact_service +): + """Input uploads follow the same artifact contract for every root type.""" + model = testing_utils.MockModel.create(responses=["reply", "reply"]) + child = LlmAgent(name="child", model=model) + root = child + if root_kind == "workflow": + root = Workflow(name="wf", edges=[(START, child)]) + elif root_kind == "composite": + root = SequentialAgent(name="pipeline", sub_agents=[child]) + sessions = InMemorySessionService() + artifacts = InMemoryArtifactService() + session = await sessions.create_session( + app_name=TEST_APP_ID, user_id=TEST_USER_ID + ) + runner = Runner( + app_name=TEST_APP_ID, + **({"node": root} if root_kind == "workflow" else {"agent": root}), + session_service=sessions, + artifact_service=artifacts if has_artifact_service else None, + plugins=[SaveFilesAsArtifactsPlugin(attach_file_reference=False)] + if use_plugin + else [], + ) + config = RunConfig(**( + {"save_input_blobs_as_artifacts": save_blobs} + if save_blobs is not None + else {} + )) + scope = dict( + app_name=TEST_APP_ID, user_id=TEST_USER_ID, session_id=session.id + ) + try: + for turn in range(2): + upload = types.Part.from_bytes(data=b"hello", mime_type="text/plain") + upload.inline_data.display_name = "upload.txt" + message = types.UserContent( + parts=[types.Part(text="inspect"), upload, types.Part(text="please")] + ) + events = [ + event + async for event in runner.run_async( + user_id=TEST_USER_ID, + session_id=session.id, + new_message=message, + run_config=config, + ) + ] + stored = await sessions.get_session(**scope) + user_event = [event for event in stored.events if event.author == "user"][ + -1 + ] + filename = ( + "upload.txt" + if use_plugin + else f"artifact_{user_event.invocation_id}_1" + ) + keys = await artifacts.list_artifact_keys(**scope) + if has_artifact_service and (save_blobs or use_plugin): + assert len(keys) == (1 if use_plugin else turn + 1) + assert filename in keys + versions = await artifacts.list_versions(**scope, filename=filename) + assert versions == (list(range(turn + 1)) if use_plugin else [0]) + saved = await artifacts.load_artifact(**scope, filename=filename) + assert saved == upload + expected = types.Part( + text=f'[Uploaded Artifact: "{filename}"]' + if use_plugin + else f"Uploaded file: {filename}. It is saved into artifacts" + ) + else: + assert keys == [] + expected = upload + assert user_event.content.parts == [ + types.Part(text="inspect"), + expected, + types.Part(text="please"), + ] + assert model.requests[-1].contents[-1].parts == user_event.content.parts + assert any(event.content for event in events) + finally: + await runner.close() + + if __name__ == "__main__": pytest.main([__file__])