-
Notifications
You must be signed in to change notification settings - Fork 3.3k
feat: Add progressive streaming for run_async via ProgressiveTool (partial progress + final result) #3564
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
sandangel
wants to merge
13
commits into
google:main
from
sandangel:feature/nonlive-runner-streaming-tools
Closed
feat: Add progressive streaming for run_async via ProgressiveTool (partial progress + final result) #3564
Changes from 2 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
d74cfc6
feat: Add progressive streaming for run_async via ProgressiveTool (pa…
ac-machache 65396a2
Merge remote-tracking branch 'origin/main' into feature/nonlive-runne…
sandangel 0b6dc6f
Merge branch 'main' into feature/nonlive-runner-streaming-tools
sandangel a1180e5
chore: implement suggested refactor for argument preparation in Progr…
sandangel 5d23673
Merge branch 'main' into feature/nonlive-runner-streaming-tools
sandangel 61a9f28
Merge branch 'main' into feature/nonlive-runner-streaming-tools
sandangel 33de05d
chore: format with pyink and isort
sandangel 7c1dce5
chore: fix tests failing
sandangel 495dc5c
chore fix tests
sandangel 63e3b20
remove no need
sandangel b2261eb
Merge branch 'main' into feature/nonlive-runner-streaming-tools
sandangel 668f156
Merge branch 'main' into feature/nonlive-runner-streaming-tools
sandangel 1267b48
Merge branch 'main' into feature/nonlive-runner-streaming-tools
sandangel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| # 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__ import annotations | ||
|
|
||
| from typing import Any | ||
| from typing import AsyncGenerator | ||
|
|
||
| from .function_tool import FunctionTool | ||
| from .tool_context import ToolContext | ||
|
|
||
|
|
||
| class ProgressiveFunctionTool(FunctionTool): | ||
| """A FunctionTool that can stream progress updates during run_async. | ||
|
|
||
| Implement `progress_stream` to yield intermediate progress payloads. | ||
| The final result for model consumption must be returned by `run_async`. | ||
| """ | ||
|
|
||
| async def progress_stream( | ||
| self, | ||
| *, | ||
| args: dict[str, Any], | ||
| tool_context: ToolContext, | ||
| ) -> AsyncGenerator[Any, None]: | ||
| """Yields progress updates while the tool is executing. | ||
|
|
||
| Subclasses should override this method to emit progress objects. The last | ||
| item yielded here does not need to be the final result; the final result | ||
| should be returned by `run_async`. | ||
| """ | ||
| raise NotImplementedError( | ||
| f"{type(self).__name__}.progress_stream is not implemented" | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| # 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__ import annotations | ||
|
|
||
| import asyncio | ||
| import inspect | ||
| from typing import Any | ||
| from typing import Optional | ||
|
|
||
| from ..utils.context_utils import Aclosing | ||
| from .function_tool import FunctionTool | ||
| from .progressive_function_tool import ProgressiveFunctionTool | ||
| from .tool_context import ToolContext | ||
|
|
||
|
|
||
| class ProgressiveTool(ProgressiveFunctionTool): | ||
| """Wraps a regular async function to emit progress during run_async. | ||
|
|
||
| Usage: | ||
| from google.adk.tools.progressive_tool import ProgressiveTool | ||
| ProgressiveTool(my_async_function) | ||
|
|
||
| Supported function shapes: | ||
| - async generator function: yields are treated as progress; last yielded | ||
| value is treated as the final result. | ||
| - async function with optional `progress` or `progress_callback` parameter: | ||
| the wrapper injects a reporter callable that streams progress; the return | ||
| value of the function is treated as the final result. | ||
| - async function without any progress parameter: no progress is emitted; the | ||
| return value is treated as the final result. | ||
| """ | ||
|
|
||
| def __init__(self, func): | ||
| # Initialize as FunctionTool to extract name/description and signature logic | ||
| FunctionTool.__init__(self, func) | ||
| self._results_by_call_id: dict[str, Any] = {} | ||
| # Hide internal progress params from function declaration so the model is | ||
| # never prompted for them and schema parsing doesn't fail. | ||
| try: | ||
| ignore_list = list(getattr(self, '_ignore_params', [])) | ||
| except Exception: | ||
| ignore_list = [] | ||
| for p in ('progress', 'progress_callback'): | ||
| if p not in ignore_list: | ||
| ignore_list.append(p) | ||
| self._ignore_params = ignore_list | ||
|
|
||
| async def progress_stream( | ||
| self, | ||
| *, | ||
| args: dict[str, Any], | ||
| tool_context: ToolContext, | ||
| ) -> asyncio.AsyncGenerator[Any, None]: | ||
| signature = inspect.signature(self.func) | ||
| valid_params = {param for param in signature.parameters} | ||
|
|
||
| # Build args for the wrapped function | ||
| args_to_call = {k: v for k, v in args.items() if k in valid_params} | ||
| if 'tool_context' in valid_params: | ||
| args_to_call['tool_context'] = tool_context | ||
|
sandangel marked this conversation as resolved.
|
||
|
|
||
| call_id: Optional[str] = tool_context.function_call_id | ||
|
|
||
| # Async generator function: yield directly and capture last item | ||
| if inspect.isasyncgenfunction(self.func): | ||
| last: Any = None | ||
| async with Aclosing(self.func(**args_to_call)) as agen: | ||
| async for item in agen: | ||
| last = item | ||
| yield item | ||
| if call_id: | ||
| self._results_by_call_id[call_id] = last | ||
| return | ||
|
|
||
| # Coroutine function: run in background, capture progress via callback | ||
| # Determine which progress parameter to use if present | ||
| progress_param: Optional[str] = None | ||
| if 'progress' in valid_params: | ||
| progress_param = 'progress' | ||
| elif 'progress_callback' in valid_params: | ||
| progress_param = 'progress_callback' | ||
|
|
||
| queue: asyncio.Queue[Any] = asyncio.Queue() | ||
|
|
||
| async def _report_progress(payload: Any): | ||
| await queue.put(payload) | ||
|
|
||
| if progress_param: | ||
| args_to_call[progress_param] = _report_progress | ||
|
|
||
| result_box: dict[str, Any] = {} | ||
|
|
||
| async def _run_and_capture(): | ||
| result_box['value'] = await self.func(**args_to_call) | ||
|
|
||
| task = asyncio.create_task(_run_and_capture()) | ||
|
|
||
| # Drain progress while task runs | ||
| try: | ||
| while True: | ||
| if task.done() and queue.empty(): | ||
| break | ||
| try: | ||
| item = await asyncio.wait_for(queue.get(), timeout=0.1) | ||
| yield item | ||
| except asyncio.TimeoutError: | ||
| await asyncio.sleep(0) | ||
| continue | ||
| finally: | ||
| # Ensure task completion / propagate exception | ||
| await task | ||
|
|
||
| if call_id: | ||
| self._results_by_call_id[call_id] = result_box.get('value') | ||
|
|
||
| async def run_async( | ||
| self, *, args: dict[str, Any], tool_context: ToolContext | ||
| ) -> Any: | ||
| """Return final result. If progress_stream already ran, use captured value.""" | ||
| call_id: Optional[str] = tool_context.function_call_id | ||
| if call_id and call_id in self._results_by_call_id: | ||
| return self._results_by_call_id.pop(call_id) | ||
|
|
||
| # Fallback: invoke function directly if progress_stream wasn't used | ||
| signature = inspect.signature(self.func) | ||
| valid_params = {param for param in signature.parameters} | ||
| args_to_call = {k: v for k, v in args.items() if k in valid_params} | ||
| if 'tool_context' in valid_params: | ||
| args_to_call['tool_context'] = tool_context | ||
|
|
||
| if inspect.isasyncgenfunction(self.func): | ||
| # Consume generator fully; return last item | ||
| last: Any = None | ||
| async with Aclosing(self.func(**args_to_call)) as agen: | ||
| async for item in agen: | ||
| last = item | ||
| return last | ||
|
|
||
| # Coroutine function | ||
| return await self.func(**args_to_call) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.