You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hello!
I am attempting to handle 429 Too Many Requests errors when executing tools in a pydantic-aiAgent using the tenacity library for retries. However, the retry mechanism only works when applied to the function that runs the entire agent (e.g., run_agent). This approach is not ideal because restarting the agent from scratch for each 429 error is inefficient.
When I attempt to apply the @retry decorator to individual tools (such as fetch_website_content and analyze_competition), the retry logic does not trigger as expected. Instead, the agent fails immediately when encountering a 429 error within a tool.
Code Snippets
Retry Decorator Implementation
fromtenacityimportretry, stop_after_attempt, wait_fixed, retry_if_exception, before_sleep_logimportloggingMAX_RETRY_ATTEMPTS=3RETRY_WAIT_SECONDS=60RETRY_STATUS_CODES= {429, 503, 504, 500}
logger=logging.getLogger(__name__)
defis_retryable_exception(exception):
ifhasattr(exception, "response") andgetattr(exception.response, "status_code", None) inRETRY_STATUS_CODES:
logging.warning("Retrying due to status code...")
returnTrueelifisinstance(exception, Exception) andany(str(code) instr(exception) forcodeinRETRY_STATUS_CODES):
logging.warning("Retrying due to matching error message...")
returnTruereturnFalse
Applying Retry to Tools
@retry(stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),wait=wait_fixed(RETRY_WAIT_SECONDS),retry=retry_if_exception(is_retryable_exception),reraise=True,before_sleep=before_sleep_log(logger, logging.WARNING),)@swot_agent.tool(retries=3)asyncdeffetch_website_content(_ctx: RunContext[SwotAgentDeps], url: str) ->str:
"""Fetches the HTML content of the given URL."""asyncwithhttpx.AsyncClient(follow_redirects=True) ashttp_client:
try:
response=awaithttp_client.get(url)
response.raise_for_status()
returnresponse.textexcepthttpx.HTTPErrorase:
logging.info(f"Request failed: {str(e)}")
raisee
Retry Works Only on the Agent Run
@retry(stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),wait=wait_fixed(RETRY_WAIT_SECONDS),retry=retry_if_exception(is_retryable_exception),reraise=True,before_sleep=before_sleep_log(logger, logging.WARNING),)asyncdefrun_agent(url: str=ANALYZE_URL, deps: SwotAgentDeps=SwotAgentDeps()) ->SwotAnalysis|Exception:
"""Runs the SWOT analysis agent."""try:
result=awaitswot_agent.run(
f"Perform a comprehensive SWOT analysis for this product: {url}",
deps=deps,
)
returnresult.dataexceptExceptionase:
logging.exception(f"Error during agent run: {e}")
raisee
Questions
Does pydantic-ai handle exceptions raised within tools in a way that interferes with tenacity’s retry mechanism?
Is there a recommended way to handle retries for individual tool executions without restarting the whole agent?
Are there any known limitations or interactions between pydantic-ai's tool execution and external retry decorators like tenacity?
Additional Context
The agent is built using pydantic-ai with a VertexAIModel backend.
Tools are defined using @swot_agent.tool() and are expected to handle HTTP requests and external API calls.
The issue occurs when executing tools that make requests to external services like Gemini AI or HTTP endpoints.
Any guidance or recommended fixes would be appreciated!
The text was updated successfully, but these errors were encountered:
Hello!
I am attempting to handle
429 Too Many Requests
errors when executing tools in apydantic-ai
Agent using thetenacity
library for retries. However, the retry mechanism only works when applied to the function that runs the entire agent (e.g.,run_agent
). This approach is not ideal because restarting the agent from scratch for each 429 error is inefficient.When I attempt to apply the
@retry
decorator to individual tools (such asfetch_website_content
andanalyze_competition
), the retry logic does not trigger as expected. Instead, the agent fails immediately when encountering a 429 error within a tool.Code Snippets
Retry Decorator Implementation
Applying Retry to Tools
Retry Works Only on the Agent Run
Questions
pydantic-ai
handle exceptions raised within tools in a way that interferes withtenacity
’s retry mechanism?pydantic-ai
's tool execution and external retry decorators liketenacity
?Additional Context
pydantic-ai
with aVertexAIModel
backend.@swot_agent.tool()
and are expected to handle HTTP requests and external API calls.Any guidance or recommended fixes would be appreciated!
The text was updated successfully, but these errors were encountered: