-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Refactor callback system to eliminate code duplication #3113
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
Open
jaywang172
wants to merge
14
commits into
google:main
Choose a base branch
from
jaywang172:refactor/callback-pipeline
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
8338ae0
refactor: introduce unified callback pipeline system
jaywang172 68cb12e
refactor: address code review feedback
jaywang172 db24b0d
refactor: optimize CallbackExecutor for better performance
jaywang172 aaf3c19
refactor: Phase 4+5 - eliminate all canonical_*_callbacks methods
jaywang172 96a0749
refactor: use CallbackPipeline consistently in all callback execution…
jaywang172 90b4d2a
refactor: return copy of callbacks list to improve encapsulation
jaywang172 e033737
fix: address bot feedback - remove CallbackExecutor and redundant checks
jaywang172 dedc36d
Delete COMPLETE_REVIEW_CHECKLIST.md
jaywang172 76a98f8
Delete REFACTORING_FINAL_SUMMARY.md
jaywang172 08de784
Delete RESPONSE_TO_JACKSUNWEI.md
jaywang172 9cf4759
Delete STATUS_SUMMARY.md
jaywang172 907d1b6
fix: add missing normalize_callbacks import in llm_agent.py
jaywang172 0208d09
refactor: simplify has_callbacks() to use idiomatic Python
jaywang172 3549daf
refactor: complete on_tool_error_callback migration to CallbackPipeli…
jaywang172 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| # 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. | ||
|
|
||
| """Unified callback pipeline system for ADK. | ||
|
|
||
| This module provides a unified way to handle all callback types in ADK, | ||
| eliminating code duplication and improving maintainability. | ||
|
|
||
| Key components: | ||
| - CallbackPipeline: Generic pipeline executor for callbacks | ||
| - normalize_callbacks: Helper to standardize callback inputs | ||
|
|
||
| Example: | ||
| >>> # Normalize callbacks | ||
| >>> callbacks = normalize_callbacks(agent.before_model_callback) | ||
| >>> | ||
| >>> # Execute pipeline | ||
| >>> pipeline = CallbackPipeline(callbacks=callbacks) | ||
| >>> result = await pipeline.execute(callback_context, llm_request) | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import inspect | ||
| from typing import Any | ||
| from typing import Callable | ||
| from typing import Generic | ||
| from typing import Optional | ||
| from typing import TypeVar | ||
| from typing import Union | ||
|
|
||
|
|
||
| TOutput = TypeVar('TOutput') | ||
|
|
||
|
|
||
| class CallbackPipeline(Generic[TOutput]): | ||
| """Unified callback execution pipeline. | ||
|
|
||
| This class provides a consistent way to execute callbacks with the following | ||
| features: | ||
| - Automatic sync/async callback handling | ||
| - Early exit on first non-None result | ||
| - Type-safe through generics | ||
| - Minimal performance overhead | ||
|
|
||
| The pipeline executes callbacks in order and returns the first non-None | ||
| result. If all callbacks return None, the pipeline returns None. | ||
|
|
||
| Example: | ||
| >>> async def callback1(ctx, req): | ||
| ... return None # Continue to next callback | ||
| >>> | ||
| >>> async def callback2(ctx, req): | ||
| ... return LlmResponse(...) # Early exit, this is returned | ||
| >>> | ||
| >>> pipeline = CallbackPipeline([callback1, callback2]) | ||
| >>> result = await pipeline.execute(context, request) | ||
| >>> # result is the return value of callback2 | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| callbacks: Optional[list[Callable]] = None, | ||
| ): | ||
| """Initializes the callback pipeline. | ||
|
|
||
| Args: | ||
| callbacks: List of callback functions. Can be sync or async. | ||
| Callbacks are executed in the order provided. | ||
| """ | ||
| self._callbacks = callbacks or [] | ||
|
|
||
| async def execute( | ||
| self, | ||
| *args: Any, | ||
| **kwargs: Any, | ||
| ) -> Optional[TOutput]: | ||
| """Executes the callback pipeline. | ||
|
|
||
| Callbacks are executed in order. The pipeline returns the first non-None | ||
| result (early exit). If all callbacks return None, returns None. | ||
|
|
||
| Both sync and async callbacks are supported automatically. | ||
|
|
||
| Args: | ||
| *args: Positional arguments passed to each callback | ||
| **kwargs: Keyword arguments passed to each callback | ||
|
|
||
| Returns: | ||
| The first non-None result from callbacks, or None if all callbacks | ||
| return None. | ||
|
|
||
| Example: | ||
| >>> result = await pipeline.execute( | ||
| ... callback_context=ctx, | ||
| ... llm_request=request, | ||
| ... ) | ||
| """ | ||
| for callback in self._callbacks: | ||
| result = callback(*args, **kwargs) | ||
|
|
||
| # Handle async callbacks | ||
| if inspect.isawaitable(result): | ||
| result = await result | ||
|
|
||
| # Early exit: return first non-None result | ||
| if result is not None: | ||
| return result | ||
|
|
||
| return None | ||
|
|
||
| def add_callback(self, callback: Callable) -> None: | ||
| """Adds a callback to the pipeline. | ||
|
|
||
| Args: | ||
| callback: The callback function to add. Can be sync or async. | ||
| """ | ||
| self._callbacks.append(callback) | ||
|
|
||
| def has_callbacks(self) -> bool: | ||
| """Checks if the pipeline has any callbacks. | ||
|
|
||
| Returns: | ||
| True if the pipeline has callbacks, False otherwise. | ||
| """ | ||
| return bool(self._callbacks) | ||
|
|
||
| @property | ||
| def callbacks(self) -> list[Callable]: | ||
| """Returns a copy of the list of callbacks in the pipeline. | ||
|
|
||
| Returns: | ||
| List of callback functions. | ||
| """ | ||
| return self._callbacks.copy() | ||
|
|
||
|
|
||
| def normalize_callbacks( | ||
| callback: Union[None, Callable, list[Callable]] | ||
| ) -> list[Callable]: | ||
| """Normalizes callback input to a list. | ||
|
|
||
| This function replaces all the canonical_*_callbacks properties in | ||
| BaseAgent and LlmAgent by providing a single utility to standardize | ||
| callback inputs. | ||
|
|
||
| Args: | ||
| callback: Can be: | ||
| - None: Returns empty list | ||
| - Single callback: Returns list with one element | ||
| - List of callbacks: Returns the list as-is | ||
|
|
||
| Returns: | ||
| Normalized list of callbacks. | ||
|
|
||
| Example: | ||
| >>> normalize_callbacks(None) | ||
| [] | ||
| >>> normalize_callbacks(my_callback) | ||
| [my_callback] | ||
| >>> normalize_callbacks([cb1, cb2]) | ||
| [cb1, cb2] | ||
|
|
||
| Note: | ||
| This function eliminates 6 duplicate canonical_*_callbacks methods: | ||
| - canonical_before_agent_callbacks | ||
| - canonical_after_agent_callbacks | ||
| - canonical_before_model_callbacks | ||
| - canonical_after_model_callbacks | ||
| - canonical_before_tool_callbacks | ||
| - canonical_after_tool_callbacks | ||
| """ | ||
| if callback is None: | ||
| return [] | ||
| if isinstance(callback, list): | ||
| return callback | ||
| return [callback] | ||
|
|
||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The PR description highlights the goal of strong type safety. While
TOutputprovides type safety for return values, the input arguments are typed as*args: Any, **kwargs: Any, which bypasses static type checking for callback arguments.To enhance type safety and ensure all callbacks within a pipeline share a compatible signature, consider using
typing.ParamSpec. This will allowmypyto validate the arguments passed topipeline.execute()against the expected signature of the callbacks. This change would make theCallbackPipelinemore robust and better align with the stated goal of strong type safety.Here's an example of how you could apply this: