feat(plugins): add LlmResiliencePlugin with retries and model fallbacks#90
feat(plugins): add LlmResiliencePlugin with retries and model fallbacks#90chillum-codeX wants to merge 5 commits intogoogle:mainfrom
Conversation
Adds a new plugin for handling transient LLM errors with:
- Configurable retries with exponential backoff + jitter
- Transient error detection (HTTP 429/500/502/503/504, httpx timeouts)
- Optional model fallbacks when primary model fails
- Support for both async generator and coroutine LLM providers
Usage:
from google.adk_community.plugins import LlmResiliencePlugin
runner = Runner(
...,
plugins=[LlmResiliencePlugin(max_retries=3, fallback_models=['gemini-1.5-flash'])]
)
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 introduces a new 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
|
There was a problem hiding this comment.
Code Review
This pull request introduces a very useful LlmResiliencePlugin for handling transient LLM errors through retries and fallbacks. The implementation is solid, with good handling of both streaming and non-streaming responses, and includes comprehensive unit tests for the main success and fallback paths.
I've identified a critical issue in the error handling logic that prevents the retry_on_exceptions parameter from working as intended. I've also included a few suggestions to improve maintainability, robustness, and test coverage. Once the critical issue is addressed, this will be a great addition to the community plugins.
| if self.retry_on_exceptions is not None and not isinstance( | ||
| error, self.retry_on_exceptions | ||
| ): | ||
| # If user provided an explicit exception tuple and it doesn't match, | ||
| # optionally still retry on transient HTTP-ish errors. | ||
| if not _is_transient_error(error): | ||
| return None | ||
| else: | ||
| # If user did not provide explicit list, rely on our transient heuristic | ||
| if not _is_transient_error(error): | ||
| # Non-transient error → don't handle | ||
| return None |
There was a problem hiding this comment.
There's a logical issue in how errors are evaluated for retries. The current implementation effectively ignores the retry_on_exceptions parameter because it requires _is_transient_error(error) to be true in all cases. If a user provides a custom exception type that is not considered a transient error by _is_transient_error, the plugin will fail to retry on it.
The logic should be to retry if the error is either in retry_on_exceptions OR it's a transient error. Here is a corrected implementation that achieves this:
if self.retry_on_exceptions and isinstance(error, self.retry_on_exceptions):
# User explicitly wants to retry on this exception type.
pass
elif not _is_transient_error(error):
# Not an explicit exception and not a transient error, so don't handle.
return NoneThere was a problem hiding this comment.
Thanks for catching this! You're right — the original logic effectively ignored retry_on_exceptions. Fixed to properly retry if error is in retry_on_exceptions OR is a transient error. Also added a test case to verify custom exception types work correctly.
Fixed the critical logic issue:
What changed:
Before (broken):
if self.retry_on_exceptions is not None and not isinstance(error, self.retry_on_exceptions):
if not _is_transient_error(error):
return None
else:
if not _is_transient_error(error):
return None
This required _is_transient_error() to be true in ALL cases.
After (fixed):
if self.retry_on_exceptions and isinstance(error, self.retry_on_exceptions):
pass # User explicitly wants to retry on this exception type
elif not _is_transient_error(error):
return None # Not explicit and not transient, don't handle
Now retries if error is in retry_on_exceptions OR is a transient error.
Also added a test case to verify custom exception types work correctly.
| if isinstance(err, httpx.HTTPStatusError): | ||
| try: | ||
| return int(err.response.status_code) | ||
| except Exception: |
There was a problem hiding this comment.
Catching a broad Exception can hide unexpected bugs and makes debugging harder. It's better to catch only the specific exceptions you anticipate might be raised during the status code extraction, such as AttributeError, ValueError, or TypeError.
| except Exception: | |
| except (AttributeError, ValueError, TypeError): |
There was a problem hiding this comment.
Good point — narrowed to (AttributeError, ValueError, TypeError) as suggested
| # Determine streaming mode | ||
| streaming_mode = getattr( | ||
| invocation_context.run_config, "streaming_mode", None | ||
| ) | ||
| stream = False | ||
| try: | ||
| # Only SSE streaming is supported in generate_content_async | ||
| from google.adk.agents.run_config import StreamingMode | ||
|
|
||
| stream = streaming_mode == StreamingMode.SSE | ||
| except (ImportError, AttributeError): | ||
| pass |
There was a problem hiding this comment.
The logic to determine the streaming mode is duplicated in _retry_same_model (lines 240-251) and _try_fallbacks (lines 291-301). To improve maintainability and follow the DRY (Don't Repeat Yourself) principle, consider extracting this block into a private helper method, for example _is_sse_streaming(self, invocation_context: InvocationContext) -> bool.
There was a problem hiding this comment.
Good suggestion — extracted the streaming mode detection into _is_sse_streaming() helper method to follow DRY principle.
| return invocation_context | ||
|
|
||
|
|
||
| class TestLlmResiliencePlugin(IsolatedAsyncioTestCase): |
There was a problem hiding this comment.
The test suite is missing coverage for the retry_on_exceptions parameter. Adding a test case for this feature would have likely caught the logical bug in on_model_error_callback and would ensure it works as expected in the future.
Consider adding a test similar to this:
async def test_retry_on_custom_exception(self):
class MyCustomError(Exception):
pass
class CustomErrorModel(BaseLlm):
model: str = "custom-error-model"
call_count = 0
@classmethod
def supported_models(cls) -> list[str]:
return ["custom-error-model"]
async def generate_content_async(
self, llm_request: LlmRequest, stream: bool = False
) -> AsyncGenerator[LlmResponse, None]:
CustomErrorModel.call_count += 1
if CustomErrorModel.call_count == 1:
raise MyCustomError("Custom error!")
yield LlmResponse(
content=types.Content(parts=[types.Part.from_text("Success!")]),
partial=False
)
LLMRegistry.register(CustomErrorModel)
agent = LlmAgent(name="agent", model="custom-error-model")
invocation_context = await create_invocation_context(agent)
plugin = LlmResiliencePlugin(
max_retries=1,
retry_on_exceptions=(MyCustomError,)
)
llm_request = LlmRequest(contents=[])
# The plugin should catch MyCustomError and retry.
result = await plugin.on_model_error_callback(
callback_context=invocation_context,
llm_request=llm_request,
error=MyCustomError(),
)
self.assertIsNotNone(result)
self.assertEqual(result.content.parts[0].text, "Success!")
self.assertEqual(CustomErrorModel.call_count, 2)There was a problem hiding this comment.
Thanks for the suggestion! I've added a comprehensive test test_retry_on_custom_exception_with_fail_then_succeed_model that uses a CustomErrorModel with a class-level call_count to verify the actual retry mechanism works end-to-end. The model fails on the first call and succeeds on retry, and the test asserts call_count == 2 to confirm the retry happened.
…ptions The previous logic required _is_transient_error() to be true in all cases, effectively ignoring the retry_on_exceptions parameter. Now the plugin will retry if the error is either in retry_on_exceptions OR is a transient error. Added test case to verify custom exception types trigger retry correctly.
Catch only AttributeError, ValueError, TypeError instead of broad Exception.
Removes duplicated logic in _retry_same_model and _try_fallbacks (DRY).
…ed model Add test_retry_on_custom_exception_with_fail_then_succeed_model that verifies the actual retry mechanism works end-to-end with a custom exception type. Uses a CustomErrorModel that fails on first call and succeeds on retry.
9134caf to
f83739d
Compare
Adds a new plugin for handling transient LLM errors with:
Usage:
from google.adk_community.plugins import LlmResiliencePlugin
runner = Runner( ..., plugins=[LlmResiliencePlugin(max_retries=3, fallback_models=['gemini-1.5-flash'])] )