adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Add Built-in Retry Mechanism for API Errors (e.g., 429 Too Many Requests) in LLM Agent

Open darkmars27 opened this issue 1 year ago • 12 comments

** Please make sure you read the contribution guide and file the issues in the right place. ** Contribution guide.

Statement: Before submitting this request, I have reviewed the ADK documentation & python code and existing issues and have not found any readily available or clearly documented built-in retry mechanisms for the LLM Agent, specifically for handling API errors like 429 Too Many Requests. If such an implementation exists, please guide me to the relevant documentation.

Is your feature request related to a problem? Please describe. I am frequently encountering 429 Too Many Requests errors when using the LLM Agent within the Google ADK. The current implementation does not provide any direct or convenient mechanism to handle these errors, specifically for retries. This leads to failed requests and interruptions in our application's workflow, requiring manual intervention or the implementation of complex, external retry logic.

Describe the solution you'd like I would like to request the addition of a built-in, configurable retry mechanism for the LLM Agent within the Google ADK. This mechanism should automatically handle transient API errors, such as 429 Too Many Requests, 500 Internal Server Error, 503 Service Unavailable, etc., by implementing an exponential backoff strategy with configurable parameters.

Ideally, this would involve:

  • Automatic Retries: The LLM Agent should automatically retry failed requests based on a predefined set of HTTP status codes.
  • Configurable Backoff: Users should be able to configure parameters like: Maximum number of retries. Initial backoff delay. Maximum backoff delay.
  • Error Handling: A clear way to differentiate between retriable and non-retriable errors, allowing for appropriate handling of persistent issues.

Describe alternatives you've considered I have considered using the HttpOptions base_url parameter to route requests through a custom proxy or service that would implement the retry logic. However, this approach introduces unnecessary overhead and complexity:

  • Additional Hop: It adds an extra network hop between our application and the Google API, potentially increasing latency and introducing a new point of failure.

  • Maintenance Burden: It requires us to deploy, manage, and maintain an additional proxy service, increasing operational overhead.

  • Security Concerns: Depending on the proxy implementation, it might introduce additional security considerations.

Additional context The lack of a built-in retry mechanism makes integrating the LLM Agent into robust, production-ready applications challenging. Many other SDKs and client libraries for interacting with cloud services provide such functionality out-of-the-box, significantly simplifying error handling and improving application resilience. Implementing this feature would greatly enhance the developer experience and the reliability of applications built using the Google ADK's LLM Agent.

darkmars27 avatar Jun 06 '25 16:06 darkmars27

I too would like such a feature as I've been getting intermittent 503 UNAVAILABLE errors from Vertex AI

halfpasttense avatar Jun 12 '25 02:06 halfpasttense

Use LiteLLM's Built-in Retry mechanism. You can also self patch file that is handling that LiteLlm

from google.adk.models.lite_llm import LiteLlm

root_agent = LlmAgent(
    model=LiteLlm(
        model="gemini/gemini-2.5-pro-preview-06-05",
        api_key=os.getenv("GOOGLE_API_KEY"),
    ),
    global_instruction=GLOBAL_INSTRUCTION,
    instruction=INSTRUCTION,
    name=configs.agent_settings.name,
    tools=[
        web_search_tool,
        web_learner_tool
    ]
)

Or from patched file:

from .utils.lite_llm import LiteLlm

petitoff avatar Jun 12 '25 23:06 petitoff

@petitoff This is a decent workaround but it's not a complete substitute for having built in retry without resorting to LiteLlm.

LiteLlm doesn't work with:

planner=BuiltInPlanner(thinking_config=ThinkingConfig(
        include_thoughts=True,
        thinking_budget=None,
    ))

Even with the same gemini model I get no thinking when switched to LiteLlm.

It also doesn't work with: code_executor=BuiltInCodeExecutor()

This one actually failed silently when I switched to LiteLlm. I only noticed by asking it to do multiplication of big numbers and seeing it gave incorrect answers.

halfpasttense avatar Jun 13 '25 02:06 halfpasttense

I agree, that feature would be very useful.

heungson avatar Jun 17 '25 01:06 heungson

Any plan to implement this feature?

darkmars27 avatar Jun 29 '25 23:06 darkmars27

This is more annoying than expected when you start agent tests... in a real conversation, user can simply retry, but in test, it fails...

eduardomoraish avatar Jun 30 '25 01:06 eduardomoraish

+1 for this feature

bex-e-coh avatar Jun 30 '25 23:06 bex-e-coh

Note: python genai sdk offers a retry param. It should be a matter of adding it to the underlining ADK gemini api client?.

I'd also consider offering a default retry of 3.

eliasecchig avatar Jul 04 '25 16:07 eliasecchig

+1 for this, also for current use case would the below workaround work?

from functools import cached_property

from google.adk.models.google_llm import Gemini
from google.genai import Client, types

...

class GeminiWithRetryMechanism(Gemini):
    """Gemini Model with exponential backoff retry mechanism."""

    model: str = LlmSettings.AGENT_MODEL

    @cached_property
    def api_client(self) -> Client:
        """Provides the api client with retry.

        Returns:
        The api client.
        """
        return Client(
            http_options=types.HttpOptions(
                headers=self._tracking_headers,
                retry_options=types.HttpRetryOptions(
                    attempts=5,
                    initial_delay=1,
                    max_delay=16,
                    exp_base=2.0,
                    jitter=0.5,
                    http_status_codes=[
                        429,
                        503,
                    ],  # Retry on rate limit and service unavailable
                ),
            )
        )

We then use the above defined llm class in agents.

BalasubramanyamEvani avatar Jul 15 '25 15:07 BalasubramanyamEvani

can't believe this issue is not handled yet

malek-jerbi avatar Jul 30 '25 13:07 malek-jerbi

Thanks for raising the issue and all the feedback.

A built-in retry mechanism for calls to Gemini will be released shortly (this week).

For a retry mechanism in LiteLLM, we will circle back shortly, and we'll be looking into https://github.com/google/adk-python/pull/1361 --> thank you @petitoff for the PR!

polong-lin avatar Jul 30 '25 18:07 polong-lin

Built-in retries for Gemini calls is now available in ADK v1.9.0. (Caveat: This update doesn't cover a retry mechanism via LiteLLM.)

  • [Core] Expose Gemini RetryOptions to client (1639298)

It hasn't been added to the documentation yet (we're always open to PRs for docs!), but hopefully it's straightforward to understand how to use it for now:

root_agent = Agent(
    model=Gemini(
        model='gemini-2.0-flash',
        retry_options=types.HttpRetryOptions(
	    initial_delay=1,
	    attempts=2
	    # ... Retry options from google.genai
	),
	# ...
    ),

For more details on the retry options, you can check the implementation in the underlying Python google-genai SDK, detailed in: https://github.com/googleapis/python-genai/pull/982/files

polong-lin avatar Aug 01 '25 12:08 polong-lin