Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions src/google/adk/evaluation/_retry_options_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,23 @@

from __future__ import annotations

import logging
from typing import Any

from google.auth import exceptions as auth_exceptions
from google.genai import types
import tenacity
from typing_extensions import override

from ..agents.callback_context import CallbackContext
from ..models.base_llm import BaseLlm
from ..models.google_llm import Gemini
from ..models.llm_request import LlmRequest
from ..models.llm_response import LlmResponse
from ..plugins.base_plugin import BasePlugin

logger = logging.getLogger("google_adk." + __name__)

_RETRY_HTTP_STATUS_CODES = (
408, # Request timeout.
429, # Too many requests.
Expand All @@ -37,6 +46,82 @@
exp_base=2.0,
http_status_codes=_RETRY_HTTP_STATUS_CODES,
)
_TIMEOUT_EXCEPTIONS: tuple[type[BaseException], ...] = (
TimeoutError,
auth_exceptions.TimeoutError,
)


def _delay_or_default(value: float | None, default: float) -> float:
"""Returns `default` only when `value` is None, so 0.0 is honored."""
return default if value is None else value


def _is_unretried_timeout_error(
exc: BaseException,
model: BaseLlm | None = None,
) -> bool:
"""Returns True when `exc` is a timeout not already retried by `model`."""
if not isinstance(exc, _TIMEOUT_EXCEPTIONS):
return False
Comment on lines +65 to +66

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this only catches builtin and google.auth timeouts, but a LiteLlm judge times out with litellm.Timeout (an openai.APITimeoutError) and AnthropicLlm with anthropic.APITimeoutError. neither is a TimeoutError, so the non Gemini judges from point 2 in the description still never get retried. checking the SDK classes that are already imported covers them without pulling openai or anthropic in at import time:

+import sys
 ...
+_SDK_TIMEOUT_EXCEPTIONS = (
+    ("openai", "APITimeoutError"),
+    ("anthropic", "APITimeoutError"),
+)
+
+
+def _is_timeout_error(exc: BaseException) -> bool:
+  if isinstance(exc, _TIMEOUT_EXCEPTIONS):
+    return True
+  for module_name, class_name in _SDK_TIMEOUT_EXCEPTIONS:
+    exc_type = getattr(sys.modules.get(module_name), class_name, None)
+    if exc_type is not None and isinstance(exc, exc_type):
+      return True
+  return False
 ...
-  if not isinstance(exc, _TIMEOUT_EXCEPTIONS):
+  if not _is_timeout_error(exc):
     return False

fixed this plus a test in this commit, you can just cherry pick it instead of redoing it: its-amann@1165522

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for checking this. You're right: litellm.Timeout subclasses openai.APITimeoutError, not TimeoutError, so this change does not retry it, and point 2 of the description overstated the scope. I've corrected the description.

This PR is scoped to #8075: the builtin and google.auth timeouts that the evaluators' own retry_options were meant to cover but never did. LiteLlm already forwards http_options.retry_options.attempts to LiteLLM as num_retries, so catching SDK timeouts here as well could stack a second retry layer on top of LiteLLM's. If maintainers want SDK-specific timeouts handled at the evaluator level, I'd rather do that in a follow-up that accounts for each SDK's own retries.

if isinstance(model, Gemini):
# Imported lazily to keep the module import time low.
from google.genai import _api_client

aiohttp_transient = getattr(_api_client, "_AIOHTTP_TRANSIENT_EXC", ())
if getattr(_api_client, "has_aiohttp", False) and isinstance(
exc, aiohttp_transient
):
return False
return True


def timeout_retry_kwargs(
llm_request: LlmRequest,
model: BaseLlm | None = None,
) -> dict[str, Any]:
"""Returns tenacity retry kwargs for client-side timeouts on `llm_request`.

NOTE: This implementation is intended for eval systems internal usage. Do not
take direct dependency on it.
"""
retry_options = (
llm_request.config.http_options.retry_options
if llm_request.config and llm_request.config.http_options
else None
)
if retry_options is None:
return {"stop": tenacity.stop_after_attempt(1), "reraise": True}
attempts = (
_DEFAULT_HTTP_RETRY_OPTIONS.attempts or 7
if retry_options.attempts is None
else retry_options.attempts
)
if attempts <= 1:
return {"stop": tenacity.stop_after_attempt(1), "reraise": True}
return {
"stop": tenacity.stop_after_attempt(attempts),
"retry": tenacity.retry_if_exception(
lambda e: _is_unretried_timeout_error(e, model)
),
"reraise": True,
"wait": tenacity.wait_exponential_jitter(
initial=_delay_or_default(
retry_options.initial_delay,
_DEFAULT_HTTP_RETRY_OPTIONS.initial_delay or 5.0,
),
max=_delay_or_default(
retry_options.max_delay,
_DEFAULT_HTTP_RETRY_OPTIONS.max_delay or 120.0,
),
exp_base=_delay_or_default(
retry_options.exp_base,
_DEFAULT_HTTP_RETRY_OPTIONS.exp_base or 2.0,
),
jitter=_delay_or_default(retry_options.jitter, 1.0),
),
"before_sleep": tenacity.before_sleep_log(logger, logging.INFO),
}


def add_default_retry_options_if_not_present(llm_request: LlmRequest) -> None:
Expand Down
46 changes: 30 additions & 16 deletions src/google/adk/evaluation/hallucinations_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

from google.genai import types as genai_types
from pydantic import ValidationError
import tenacity
from typing_extensions import override

from ..models.base_llm import BaseLlm
Expand All @@ -32,6 +33,7 @@
from ..utils.content_utils import extract_text_from_content
from ..utils.context_utils import Aclosing
from ._retry_options_utils import add_default_retry_options_if_not_present
from ._retry_options_utils import timeout_retry_kwargs
from .app_details import AppDetails
from .eval_case import ConversationScenario
from .eval_case import Invocation
Expand Down Expand Up @@ -539,14 +541,20 @@ async def _evaluate_nl_response(
)
add_default_retry_options_if_not_present(segmenter_llm_request)
try:
async with Aclosing(
self._judge_model.generate_content_async(segmenter_llm_request)
) as agen:
segmenter_response = await agen.__anext__()
segmenter_text = get_text_from_content(segmenter_response.content)
if segmenter_text is None:
return None, "Segmenter returned no text."
sentences = _parse_sentences(segmenter_text)
segmenter_retry_kwargs = timeout_retry_kwargs(
segmenter_llm_request, self._judge_model
)
segmenter_text = None
async for attempt in tenacity.AsyncRetrying(**segmenter_retry_kwargs):
with attempt:
async with Aclosing(
self._judge_model.generate_content_async(segmenter_llm_request)
) as agen:
segmenter_response = await agen.__anext__()
segmenter_text = get_text_from_content(segmenter_response.content)
if segmenter_text is None:
return None, "Segmenter returned no text."
sentences = _parse_sentences(segmenter_text)
except Exception as e:
return None, f"Error during sentence segmentation: {e}"

Expand Down Expand Up @@ -574,14 +582,20 @@ async def _evaluate_nl_response(
)
add_default_retry_options_if_not_present(validator_llm_request)
try:
async with Aclosing(
self._judge_model.generate_content_async(validator_llm_request)
) as agen:
validator_response = await agen.__anext__()
validator_text = get_text_from_content(validator_response.content)
if validator_text is None:
return None, "Sentence validator returned no text."
validation_results = _parse_validation_results(validator_text)
validator_retry_kwargs = timeout_retry_kwargs(
validator_llm_request, self._judge_model
)
validator_text = None
async for attempt in tenacity.AsyncRetrying(**validator_retry_kwargs):
with attempt:
async with Aclosing(
self._judge_model.generate_content_async(validator_llm_request)
) as agen:
validator_response = await agen.__anext__()
validator_text = get_text_from_content(validator_response.content)
if validator_text is None:
return None, "Sentence validator returned no text."
validation_results = _parse_validation_results(validator_text)
except Exception as e:
return None, f"Error during sentence validation: {e}"

Expand Down
41 changes: 23 additions & 18 deletions src/google/adk/evaluation/llm_as_judge.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

from google.genai import types as genai_types
from pydantic import ValidationError
import tenacity
from typing_extensions import override

from ..models.base_llm import BaseLlm
Expand All @@ -33,6 +34,7 @@
from ..models.registry import LLMRegistry
from ..utils.context_utils import Aclosing
from ._retry_options_utils import add_default_retry_options_if_not_present
from ._retry_options_utils import timeout_retry_kwargs
from .common import EvalBaseModel
from .eval_case import ConversationScenario
from .eval_case import Invocation
Expand Down Expand Up @@ -178,25 +180,28 @@ async def _evaluate_single_sample(
Returns:
A PerInvocationResult containing the evaluation score and status.
"""
async with Aclosing(
self._judge_model.generate_content_async(llm_request)
) as agen:
async for llm_response in agen:
# Non-streaming call, so there is only one response content.
auto_rater_score = (
self._convert_auto_rater_response_to_score_for_invocation(
llm_response, actual=actual, expected=expected
retry_kwargs = timeout_retry_kwargs(llm_request, self._judge_model)
async for attempt in tenacity.AsyncRetrying(**retry_kwargs):
with attempt:
async with Aclosing(
self._judge_model.generate_content_async(llm_request)
) as agen:
async for llm_response in agen:
# Non-streaming call, so there is only one response content.
auto_rater_score = (
self._convert_auto_rater_response_to_score_for_invocation(
llm_response, actual=actual, expected=expected
)
)
return PerInvocationResult(
actual_invocation=actual,
expected_invocation=expected,
score=auto_rater_score.score,
eval_status=get_eval_status(
auto_rater_score.score, self._threshold
),
rubric_scores=auto_rater_score.rubric_scores,
)
)
return PerInvocationResult(
actual_invocation=actual,
expected_invocation=expected,
score=auto_rater_score.score,
eval_status=get_eval_status(
auto_rater_score.score, self._threshold
),
rubric_scores=auto_rater_score.rubric_scores,
)
# If we reach here, the LLM didn't return any response
raise RuntimeError(
"LLM evaluation failed: no response received from judge model"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

from google.genai import types as genai_types
from pydantic import ValidationError
import tenacity
from typing_extensions import override

from ...models.base_llm import BaseLlm
Expand All @@ -28,6 +29,7 @@
from ...models.registry import LLMRegistry
from ...utils.context_utils import Aclosing
from .._retry_options_utils import add_default_retry_options_if_not_present
from .._retry_options_utils import timeout_retry_kwargs
from ..eval_case import ConversationScenario
from ..eval_case import Invocation
from ..eval_metrics import EvalMetric
Expand Down Expand Up @@ -397,8 +399,13 @@ async def _evaluate_stop_signal_turn(
)

async def _sample_llm(self, llm_request: LlmRequest) -> AutoRaterScore:
async with Aclosing(self._llm.generate_content_async(llm_request)) as agen:
async for llm_response in agen:
# Non-streaming call, so there is only one response content.
return self._convert_llm_response_to_score(llm_response)
retry_kwargs = timeout_retry_kwargs(llm_request, self._llm)
async for attempt in tenacity.AsyncRetrying(**retry_kwargs):
with attempt:
async with Aclosing(
self._llm.generate_content_async(llm_request)
) as agen:
async for llm_response in agen:
# Non-streaming call, so there is only one response content.
return self._convert_llm_response_to_score(llm_response)
return AutoRaterScore()
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from google.adk.evaluation.simulation.per_turn_user_simulator_quality_v1 import PerTurnUserSimulatorQualityV1
from google.adk.evaluation.simulation.user_simulator_personas import UserBehavior
from google.adk.evaluation.simulation.user_simulator_personas import UserPersona
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.genai import types
from google.genai import types as genai_types
Expand Down Expand Up @@ -1066,3 +1067,38 @@ async def mock_generate_content_async(llm_request):

assert in_flight == 0
assert cancelled_calls >= 2


async def test_sample_llm_retries_judge_timeout(mocker):
evaluator = _create_test_evaluator()
call_count = 0

async def mock_generate_content_async(llm_request):
del llm_request
nonlocal call_count
call_count += 1
if call_count == 1:
raise TimeoutError("Request timed out.")
yield LlmResponse(
content=genai_types.Content(
parts=[genai_types.Part(text='{"is_valid": "valid"}')],
role="model",
)
)

evaluator._llm = mocker.MagicMock()
evaluator._llm.generate_content_async = mock_generate_content_async
llm_request = LlmRequest(
config=genai_types.GenerateContentConfig(
http_options=genai_types.HttpOptions(
retry_options=genai_types.HttpRetryOptions(
attempts=2, initial_delay=0.0, max_delay=0.0, jitter=0.0
)
)
)
)

score = await evaluator._sample_llm(llm_request)

assert score == AutoRaterScore(score=1.0)
assert call_count == 2
47 changes: 47 additions & 0 deletions tests/unittests/evaluation/test_hallucinations_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -2328,3 +2328,50 @@ def get_steps_or_raise(actual):
await metric.evaluate_invocations(invocations)

assert cancelled


async def test_evaluate_nl_response_retries_judge_timeouts(mock_llm_registry):
del mock_llm_registry # fixture only needed for its side effect.
criterion = HallucinationsCriterion(
threshold=0.5,
judge_model_options=JudgeModelOptions(
judge_model="gemini-2.5-flash",
judge_model_config=genai_types.GenerateContentConfig(
http_options=genai_types.HttpOptions(
retry_options=genai_types.HttpRetryOptions(
attempts=2, initial_delay=0.0, max_delay=0.0, jitter=0.0
)
)
),
num_samples=1,
),
)
metric = HallucinationsV1Evaluator(
EvalMetric(
metric_name="hallucinations_v1", threshold=0.5, criterion=criterion
)
)
responses = [
None,
"<sentence>s</sentence>",
None,
(
"sentence: s\nlabel: supported\nrationale: r\n"
"supporting_excerpt: null\ncontradicting_excerpt: null"
),
]

async def mock_generate(llm_request):
del llm_request
text = responses.pop(0)
if text is None:
raise TimeoutError("Request timed out.")
yield LlmResponse(
content=genai_types.Content(parts=[genai_types.Part(text=text)])
)

metric._judge_model.generate_content_async = mock_generate
score, _ = await metric._evaluate_nl_response("nl", "ctx")

assert score == 1.0
assert not responses
Loading