Skip to content

Comments

feat(plugins): add LlmResiliencePlugin with retries and model fallbacks#90

Open
chillum-codeX wants to merge 5 commits intogoogle:mainfrom
chillum-codeX:feat/llm-resilience-plugin
Open

feat(plugins): add LlmResiliencePlugin with retries and model fallbacks#90
chillum-codeX wants to merge 5 commits intogoogle:mainfrom
chillum-codeX:feat/llm-resilience-plugin

Conversation

@chillum-codeX
Copy link

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'])] )

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'])]
  )
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @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 LlmResiliencePlugin designed to significantly improve the reliability of LLM interactions within the Google ADK framework. By implementing robust error handling, including configurable retries with exponential backoff and optional model fallbacks, the plugin ensures that applications can gracefully recover from transient LLM service disruptions, thereby enhancing overall system stability and user experience.

Highlights

  • Introduced LlmResiliencePlugin: A new plugin has been added to the google.adk_community.plugins module to enhance LLM interaction reliability.
  • Configurable Retries: The plugin offers configurable retry mechanisms with exponential backoff and jitter for transient LLM errors.
  • Transient Error Detection: It automatically detects and handles common transient errors, including specific HTTP status codes (429, 500, 502, 503, 504) and httpx/asyncio timeouts.
  • Model Fallbacks: Users can specify a list of fallback models to be used if the primary model fails after retries.
  • LLM Provider Compatibility: The plugin supports both async generator and coroutine-based LLM providers, ensuring broad applicability.

🧠 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
  • src/google/adk_community/init.py
    • Imported the new plugins module to make community plugins discoverable.
  • src/google/adk_community/plugins/init.py
    • Created the __init__.py file for the new plugins package, exposing LlmResiliencePlugin.
  • src/google/adk_community/plugins/llm_resilience_plugin.py
    • Added the core implementation of the LlmResiliencePlugin, including retry logic, error detection, and model fallback mechanisms.
  • tests/unittests/plugins/init.py
    • Added an empty __init__.py file to define the plugins test package.
  • tests/unittests/plugins/test_llm_resilience_plugin.py
    • Implemented comprehensive unit tests to verify the functionality of the LlmResiliencePlugin, covering retry, fallback, and error handling scenarios.
Activity
  • No activity has been recorded for this pull request yet.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines 172 to 183
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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

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 None

Copy link
Author

@chillum-codeX chillum-codeX Feb 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
except Exception:
except (AttributeError, ValueError, TypeError):

Copy link
Author

@chillum-codeX chillum-codeX Feb 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point — narrowed to (AttributeError, ValueError, TypeError) as suggested

Comment on lines 240 to 251
# 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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good suggestion — extracted the streaming mode detection into _is_sse_streaming() helper method to follow DRY principle.

return invocation_context


class TestLlmResiliencePlugin(IsolatedAsyncioTestCase):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@chillum-codeX chillum-codeX force-pushed the feat/llm-resilience-plugin branch from 9134caf to f83739d Compare February 19, 2026 10:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant