Feat/resilience plugin#4537
Feat/resilience plugin#4537chillum-codeX wants to merge 15 commits intogoogle:maingoogle/adk-python:mainfrom chillum-codeX:feat/resilience-pluginchillum-codeX/adk-python:feat/resilience-pluginCopy head branch name to clipboard
Conversation
…allbacks; tests for plugin behavior
…esiliencePlugin; import InvocationContext for typing; keep tests consistent
…nContext or Context and robust asyncgen handling
…t when importing plugins package; rely on duck-typing for context access
…n, tests, and usage
…ror; all plugin tests pass
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
Summary of ChangesHello @chillum-codeX, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the reliability of LLM interactions by introducing a centralized Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
|
Response from ADK Triaging Agent Hello @chillum-codeX, thank you for creating this PR! It looks like you have not yet signed our Contributor License Agreement (CLA). Please visit https://cla.developers.google.com/ to sign it. This information will help reviewers to review your PR more efficiently. Thanks! |
There was a problem hiding this comment.
Code Review
This pull request introduces a valuable LlmResiliencePlugin for handling transient LLM errors through retries and fallbacks. The implementation is robust, covering both async generator and coroutine-based LLM providers, and includes comprehensive unit tests for the core logic. The addition of a sample application is also very helpful for understanding its usage.
My review includes a few suggestions to improve maintainability and fix a minor issue in the sample code. Specifically, I've recommended adding type hints to a helper function, narrowing the scope of some exception handlers, and correcting the state management in the demo model to ensure it behaves as intended.
| class DemoFailThenSucceedModel(BaseLlm): | ||
| model: str = "demo-fail-succeed" | ||
| attempts: int = 0 | ||
|
|
||
| @classmethod | ||
| def supported_models(cls) -> list[str]: | ||
| return ["demo-fail-succeed"] | ||
|
|
||
| async def generate_content_async( | ||
| self, llm_request: LlmRequest, stream: bool = False | ||
| ): | ||
| # Fail for the first attempt, then succeed | ||
| self.attempts += 1 | ||
| if self.attempts < 2: | ||
| raise TimeoutError("Simulated transient failure") | ||
| yield LlmResponse( | ||
| content=types.Content( | ||
| role="model", | ||
| parts=[types.Part.from_text(text="Recovered on retry!")], | ||
| ), | ||
| partial=False, | ||
| ) |
There was a problem hiding this comment.
The stateful logic in DemoFailThenSucceedModel relies on the attempts counter being incremented across calls. However, because the agent is configured with the model name as a string (model="demo-fail-succeed"), a new instance of DemoFailThenSucceedModel is created for the initial call and for each retry attempt. This resets self.attempts to 0 for each new instance, preventing the model from succeeding after a failure as intended in this demo.
To ensure the state is shared across these distinct instances, attempts should be a true class variable, accessed via the class itself.
class DemoFailThenSucceedModel(BaseLlm):
model: str = "demo-fail-succeed"
_attempts: int = 0
@classmethod
def supported_models(cls) -> list[str]:
return ["demo-fail-succeed"]
async def generate_content_async(
self, llm_request: LlmRequest, stream: bool = False
):
# Fail for the first attempt, then succeed
DemoFailThenSucceedModel._attempts += 1
if DemoFailThenSucceedModel._attempts < 2:
raise TimeoutError("Simulated transient failure")
yield LlmResponse(
content=types.Content(
role="model",
parts=[types.Part.from_text(text="Recovered on retry!")],
),
partial=False,
)There was a problem hiding this comment.
What changed:
• Used ClassVar[int] from typing module to properly declare a class variable
• Access the counter via DemoFailThenSucceedModel.attempts instead of self._attempts
• This ensures the counter is shared across all instances created during retries
Verified:
• ✅ Sample runs correctly: Recovered on retry!
• ✅ Pushed to PR
There was a problem hiding this comment.
For better type safety and code clarity, please add type hints for the callback_context parameter and the return value of the _get_invocation_context method.
| def _get_invocation_context(self, callback_context): | |
| def _get_invocation_context( | |
| self, callback_context: CallbackContext | InvocationContext | |
| ) -> InvocationContext: |
There was a problem hiding this comment.
Using a broad except Exception: pass can hide unexpected errors and make debugging more difficult. It's better to catch only the specific exceptions you expect to handle. In this case, you're trying to guard against potential ImportError if the local import fails or AttributeError if the config structure is not as expected.
This same pattern is used in the _try_fallbacks method on lines 253-254 and should also be updated.
| except Exception: | |
| pass | |
| except (ImportError, AttributeError): | |
| pass |
There was a problem hiding this comment.
Updated both exception handlers from except ImportError: to except (ImportError, AttributeError): as suggested by the reviewer.
Adds plugin export, unit tests, resilient sample, PR body updates, and contribution note with validation evidence.
e0bb1fa to
2179788
Compare
- Add type hints and docstring to _get_invocation_context helper - Narrow exception handlers from Exception to ImportError - Fix demo model state management: use instance variable instead of class variable
Since the agent uses model name as string, new instances are created for each retry. Use typing.ClassVar to ensure the attempts counter is shared across all instances of DemoFailThenSucceedModel.
Catch only the specific exceptions expected when importing StreamingMode or accessing config attributes, rather than broad Exception.
|
Hi @chillum-codeX ,Thank you for your contribution! We appreciate you taking the time to submit this pull request. |
|
Thanks for the guidance! I've submitted the plugin to the community repo as suggested: google/adk-python-community#90 Appreciate the feedback! 🙏 |
feat(plugins): LlmResiliencePlugin – configurable retries/backoff and model fallbacks
Link to Issue or Description of Change
1. Link to an existing issue (if applicable):
2. Or, if no issue exists, describe the change:
Problem:
Production agents need first-class resilience to transient LLM/API failures
(timeouts, HTTP 429/5xx). Today, retry/fallback logic is often ad-hoc and
duplicated across projects.
Solution:
Introduce an opt-in plugin,
LlmResiliencePlugin, that handles transient LLMerrors with configurable retries (exponential backoff + jitter) and optional
model fallbacks, without modifying core runner/flow logic.
Summary
src/google/adk/plugins/llm_resilience_plugin.py.LlmResiliencePlugininsrc/google/adk/plugins/__init__.py.tests/unittests/plugins/test_llm_resilience_plugin.py:test_retry_success_on_same_modeltest_fallback_model_used_after_retriestest_non_transient_error_bubblessamples/resilient_agent.pydemo.Testing Plan
Unit Tests:
Command run:
Result summary:
Manual End-to-End (E2E) Tests:
Run sample:
Observed output:
Checklist
Additional context
Runner(..., plugins=[LlmResiliencePlugin(...)]).in follow-ups (e.g., per-exception policy, circuit breaking).