Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Bound LLM provider calls on the direct client path with a real wall-clock deadline (#8010)
pedrohsdb6019b41281d0
diff --git a/.env.example b/.env.exampleindex 08d76de2d..3e75b9398 100644--- a/.env.example+++ b/.env.example@@ -105,6 +105,14 @@ YUTORI_TOOL_SET=""LLM_KEY=""# a cheaper LLM providers to help finishing some small tasks, like custom selection or svg conversion. If empty, it will be the same as LLM_KEYSECONDARY_LLM_KEY=""+# ENFORCE_LLM_HARD_DEADLINE: On the direct AsyncOpenAI client path (OpenRouter, custom keys,+# Copilot-style endpoints), cancel a request once it outlives the timeout budget it was given.+# The provider timeout only bounds the gap between reads, so a stalled provider can otherwise hold a+# worker indefinitely. Other LLM paths (litellm router, Anthropic, UI-TARS) are not yet covered.+# Set to false to restore the old unbounded behavior on the covered path.+ENFORCE_LLM_HARD_DEADLINE=true+# LLM_HARD_DEADLINE_GRACE_SECONDS: Seconds allowed on top of that budget before the request is cancelled.+LLM_HARD_DEADLINE_GRACE_SECONDS=10# Web browser configuration for scraping:# BROWSER_TYPE: Can be either "chromium-headless" or "chromium-headful".diff --git a/skyvern/config.py b/skyvern/config.pyindex 1d530497c..1c527323a 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -410,6 +410,11 @@ class Settings(BaseSettings):WORKFLOW_COPILOT_LITE_LLM_KEY: str | None = None# COMMONLLM_CONFIG_TIMEOUT: int = 300+ # The client-side timeout is a per-read gap applied per SDK attempt, so a provider that drips+ # keep-alive bytes can hold a call open forever; the hard deadline bounds it in wall-clock time.+ # Only the direct AsyncOpenAI client path (api_handler_factory.LLMCaller) applies this today.+ ENFORCE_LLM_HARD_DEADLINE: bool = True+ LLM_HARD_DEADLINE_GRACE_SECONDS: float = Field(default=10.0, ge=0)LLM_CONFIG_MAX_TOKENS: int = 4096LLM_CONFIG_TEMPERATURE: float = 0LLM_CONFIG_SUPPORT_VISION: bool = True # Whether the model supports visiondiff --git a/skyvern/forge/sdk/api/llm/api_handler_factory.py b/skyvern/forge/sdk/api/llm/api_handler_factory.pyindex 4d5f9f384..165ec8500 100644--- a/skyvern/forge/sdk/api/llm/api_handler_factory.py+++ b/skyvern/forge/sdk/api/llm/api_handler_factory.py@@ -6,6 +6,7 @@ import reimport timeimport warningsfrom asyncio import CancelledError+from json import JSONDecodeErrorfrom typing import Any, AsyncIterator, Protocol, runtime_checkableimport litellm@@ -117,6 +118,56 @@ def _build_custom_llm_http_client(llm_key: str, llm_config: LLMConfig) -> AsyncOreturn _NoRedirectAsyncHTTPHandler()+# Deduped once per process on purpose: the reasons are a fixed, low-cardinality set, and an+# unusable timeout shape recurs on every call.+_hard_deadline_disabled_reasons: set[str] = set()+++def _log_unusable_hard_deadline_input(reason: str, value: Any) -> None:+ if reason in _hard_deadline_disabled_reasons:+ return+ _hard_deadline_disabled_reasons.add(reason)+ LOG.warning(+ "LLM hard deadline disabled for an unusable input",+ reason=reason,+ value_type=type(value).__name__,+ value=repr(value),+ )+++# The openai SDK retries a failed attempt itself, and `timeout` applies per attempt, so one+# call may legitimately span (max_retries + 1) timeouts.+def _openai_client_attempts(openai_client: Any) -> int | None:+ max_retries = openai_client.max_retries+ if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0:+ _log_unusable_hard_deadline_input("client_max_retries", max_retries)+ return None+ return max_retries + 1+++# The provider timeout is an httpx read timeout — a gap between reads, which keep-alive bytes+# reset indefinitely. Returns the wall-clock budget for one call, or None when unenforceable.+def _llm_hard_deadline_seconds(timeout: Any, attempts: int | None) -> float | None:+ if not settings.ENFORCE_LLM_HARD_DEADLINE or attempts is None:+ return None+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or timeout <= 0:+ _log_unusable_hard_deadline_input("timeout", timeout)+ return None+ deadline = attempts * float(timeout) + settings.LLM_HARD_DEADLINE_GRACE_SECONDS+ # Unreachable given the checks above and the ge=0 grace; kept so a future input can't slip a+ # non-positive deadline into asyncio.timeout, where it would cancel the call immediately.+ if deadline <= 0:+ _log_unusable_hard_deadline_input("deadline", deadline)+ return None+ return deadline+++# Some libraries re-raise a JSONDecodeError built through __new__, which leaves `doc` unset.+def _json_error_body_length(error: JSONDecodeError) -> int | None:+ doc = getattr(error, "doc", None)+ return len(doc) if isinstance(doc, str) else None++async def _validate_custom_llm_api_base(llm_key: str, llm_config: LLMConfig | LLMRouterConfig) -> None:if not is_custom_llm_key(llm_key) or SettingsManager.get_settings().ALLOW_CUSTOM_LLM_LOCAL_API_BASES:return@@ -1877,6 +1928,20 @@ class LLMAPIHandlerFactory:duration_seconds=duration_seconds,)raise SkyvernContextWindowExceededError(model=main_model_group, prompt_name=prompt_name) from e+ except JSONDecodeError as e:+ # A dead upstream can answer HTTP 200 with an empty or truncated body. Already+ # retryable through the ValueError branch below, but logged there as a token limit.+ duration_seconds = time.perf_counter() - start_time+ _llm_span.set_attribute("status", "error")+ LOG.warning(+ "LLM response body was not parseable JSON",+ llm_key=llm_key,+ model=main_model_group,+ prompt_name=prompt_name,+ body_length=_json_error_body_length(e),+ duration_seconds=duration_seconds,+ )+ raise LLMProviderErrorRetryableTask(llm_key, cause=e) from eexcept ValueError as e:duration_seconds = time.perf_counter() - start_time_llm_span.set_attribute("status", "error")@@ -2520,6 +2585,20 @@ class LLMAPIHandlerFactory:duration_seconds=duration_seconds,)raise LLMProviderError(llm_key, cause=e) from e+ except JSONDecodeError as e:+ # A dead upstream can answer HTTP 200 with an empty or truncated body, which fails+ # parsing after the status check; that is a transient fault, not a bad request.+ duration_seconds = time.perf_counter() - start_time+ _llm_span.set_attribute("status", "error")+ LOG.warning(+ "LLM response body was not parseable JSON",+ llm_key=llm_key,+ model=model_name,+ prompt_name=prompt_name,+ body_length=_json_error_body_length(e),+ duration_seconds=duration_seconds,+ )+ raise LLMProviderErrorRetryableTask(llm_key, cause=e) from eexcept Exception as e:duration_seconds = time.perf_counter() - start_time_llm_span.set_attribute("status", "error")@@ -3149,9 +3228,11 @@ class LLMCaller:)raise SkyvernContextWindowExceededError(model=self.llm_config.model_name) from eexcept litellm.exceptions.RateLimitError as e:+ # Rate limits are transient, and this path no longer leans on SDK-level retries, so+ # the step-level retry (bounded by max_retries_per_step) is what absorbs them._llm_span.set_attribute("status", "rate_limited")LOG.warning("LLM request rate limited", llm_key=self.llm_key)- raise LLMProviderError(self.llm_key, cause=e) from e+ raise LLMProviderErrorRetryableTask(self.llm_key, cause=e) from eexcept litellm.exceptions.APIError as e:_llm_span.set_attribute("status", "error")raise LLMProviderErrorRetryableTask(self.llm_key, cause=e) from e@@ -3179,10 +3260,27 @@ class LLMCaller:except RateLimitError as e:_llm_span.set_attribute("status", "rate_limited")LOG.warning("LLM request rate limited", llm_key=self.llm_key)- raise LLMProviderError(self.llm_key, cause=e) from e+ raise LLMProviderErrorRetryableTask(self.llm_key, cause=e) from eexcept APIError as e:_llm_span.set_attribute("status", "error")raise LLMProviderErrorRetryableTask(self.llm_key, cause=e) from e+ except JSONDecodeError as e:+ # A dead upstream can answer HTTP 200 with an empty or truncated body, which fails+ # parsing after the status check; that is a transient fault, not a bad request.+ _llm_span.set_attribute("status", "error")+ LOG.warning(+ "LLM response body was not parseable JSON",+ llm_key=self.llm_key,+ model=self.llm_config.model_name,+ body_length=_json_error_body_length(e),+ error=str(e),+ )+ raise LLMProviderErrorRetryableTask(self.llm_key, cause=e) from e+ except LLMProviderError:+ # Already classified (retryable or not) by the dispatch path; re-wrapping it below+ # would erase that and log it as an unexpected failure.+ _llm_span.set_attribute("status", "error")+ raiseexcept Exception as e:_llm_span.set_attribute("status", "error")LOG.exception("LLM request failed unexpectedly", llm_key=self.llm_key)@@ -3396,6 +3494,9 @@ class LLMCaller:api_key=litellm_params.get("api_key") or settings.OPENROUTER_API_KEY,base_url=litellm_params.get("api_base") or settings.OPENROUTER_API_BASE,http_client=ForgeAsyncHttpxClientWrapper(follow_redirects=False),+ # An SDK retry re-spends the whole timeout against a stalled provider; leave+ # transient failures to the step-level retry instead.+ max_retries=0,)if openai_client:# Extract OpenRouter-specific and GitHub Copilot-specific parameters@@ -3458,14 +3559,36 @@ class LLMCaller:request_extra_body.setdefault(key, value)openai_params["extra_body"] = request_extra_body+ attempts = _openai_client_attempts(openai_client) if settings.ENFORCE_LLM_HARD_DEADLINE else None+ deadline = _llm_hard_deadline_seconds(timeout, attempts)try:- completion = await openai_client.chat.completions.create(+ provider_call = openai_client.chat.completions.create(model=self.llm_key,messages=messages,extra_headers=extra_headers if extra_headers else None,timeout=timeout,**openai_params,)+ if deadline is None:+ completion = await provider_call+ else:+ try:+ async with asyncio.timeout(deadline) as deadline_scope:+ completion = await provider_call+ except TimeoutError as e:+ # A TimeoutError the scope did not raise came from inside the request;+ # relabelling it as a deadline hit would bury its real cause.+ if not deadline_scope.expired():+ raise+ LOG.warning(+ "LLM request exceeded its hard deadline",+ llm_key=self.llm_key,+ model=self.llm_config.model_name,+ timeout=timeout,+ attempts=attempts,+ deadline=deadline,+ )+ raise LLMProviderErrorRetryableTask(self.llm_key, cause=e) from e# Convert OpenAI ChatCompletion to litellm ModelResponse format# litellm.utils.convert_to_model_response_object expects a dictreturn litellm.ModelResponse(**completion.model_dump())diff --git a/tests/unit/helpers.py b/tests/unit/helpers.pyindex 66ae00ee5..791a3a0fd 100644--- a/tests/unit/helpers.py+++ b/tests/unit/helpers.py@@ -63,15 +63,17 @@ class FakeLLMResponse:class DummyLogger:def __init__(self) -> None:self.events: list[tuple[str, dict[str, Any]]] = []+ self.warnings: list[tuple[str, dict[str, Any]]] = []+ self.exceptions: list[tuple[str, dict[str, Any]]] = []def info(self, event: str, **kwargs: dict[str, Any]) -> None:self.events.append((event, kwargs))- def warning(self, *args, **kwargs) -> None: # pragma: no cover- pass+ def warning(self, event: str = "", **kwargs: Any) -> None:+ self.warnings.append((event, kwargs))- def exception(self, *args, **kwargs) -> None: # pragma: no cover- pass+ def exception(self, event: str = "", **kwargs: Any) -> None:+ self.exceptions.append((event, kwargs))def debug(self, *args, **kwargs) -> None: # pragma: no coverpassdiff --git a/tests/unit/test_api_handler_factory.py b/tests/unit/test_api_handler_factory.pyindex a665f3fce..2fab6e485 100644--- a/tests/unit/test_api_handler_factory.py+++ b/tests/unit/test_api_handler_factory.py@@ -1,5 +1,7 @@from __future__ import annotations+import asyncio+import jsonfrom asyncio import CancelledErrorfrom datetime import datetimefrom pathlib import Path@@ -7,7 +9,9 @@ from types import SimpleNamespacefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock+import httpximport litellm # type: ignore[import-not-found]+import openaiimport pytest # type: ignore[import-not-found]from skyvern.forge.sdk.api.llm import api_handler_factory@@ -18,6 +22,7 @@ from skyvern.forge.sdk.api.llm.api_handler_factory import (LLMCaller,get_org_aware_secondary_llm_api_handler,)+from skyvern.forge.sdk.api.llm.exceptions import LLMProviderErrorRetryableTaskfrom skyvern.forge.sdk.api.llm.models import LLMConfigfrom skyvern.forge.sdk.artifact.models import ArtifactTypefrom skyvern.forge.sdk.core.skyvern_context import SkyvernContext@@ -169,6 +174,7 @@ async def test_custom_openrouter_client_is_scoped_to_request(completion = MagicMock()completion.model_dump.return_value = {}client = MagicMock()+ client.max_retries = 0client.chat.completions.create = AsyncMock(return_value=completion, side_effect=request_error)client.close = AsyncMock()openai_client = MagicMock(return_value=client)@@ -184,6 +190,7 @@ async def test_custom_openrouter_client_is_scoped_to_request(await caller._dispatch_llm_call(messages=[])assert openai_client.call_args.kwargs["http_client"].follow_redirects is False+ assert openai_client.call_args.kwargs["max_retries"] == 0client.close.assert_awaited_once()@@ -215,6 +222,7 @@ async def test_openrouter_extra_body_reaches_async_openai(monkeypatch: pytest.Mocompletion = MagicMock()completion.model_dump.return_value = {"provider": "Cloudflare", "service_tier": "standard"}client = MagicMock()+ client.max_retries = 0client.chat.completions.create = AsyncMock(return_value=completion)monkeypatch.setattr(api_handler_factory, "AsyncOpenAI", MagicMock(return_value=client))monkeypatch.setattr(api_handler_factory.litellm, "ModelResponse", MagicMock())@@ -230,6 +238,275 @@ async def test_openrouter_extra_body_reaches_async_openai(monkeypatch: pytest.Moassert request_kwargs["reasoning_effort"] == "medium"+def _openrouter_caller(+ monkeypatch: pytest.MonkeyPatch,+ create: Any,+ *,+ llm_key: str = "OPENROUTER_EXAMPLE",+ max_retries: Any = 0,+) -> tuple[LLMCaller, MagicMock]:+ llm_config = _custom_llm_config("openrouter/example-model", "https://openrouter.ai/api/v1")+ monkeypatch.setattr(api_handler_factory.LLMConfigRegistry, "get_config", lambda _: llm_config)+ client = MagicMock()+ client.max_retries = max_retries+ client.chat.completions.create = create+ client.close = AsyncMock()+ monkeypatch.setattr(api_handler_factory, "AsyncOpenAI", MagicMock(return_value=client))+ monkeypatch.setattr(api_handler_factory.litellm, "ModelResponse", MagicMock())+ monkeypatch.setattr(api_handler_factory.skyvern_context, "current", lambda: None)+ monkeypatch.setattr(+ api_handler_factory,+ "llm_messages_builder_with_history",+ AsyncMock(return_value=[{"role": "user", "content": "test"}]),+ )+ return LLMCaller(llm_key), client+++def _set_hard_deadline_settings(monkeypatch: pytest.MonkeyPatch, *, enforce: bool, grace: float) -> None:+ monkeypatch.setattr(api_handler_factory.settings, "ENFORCE_LLM_HARD_DEADLINE", enforce)+ monkeypatch.setattr(api_handler_factory.settings, "LLM_HARD_DEADLINE_GRACE_SECONDS", grace)+ monkeypatch.setattr(api_handler_factory, "_hard_deadline_disabled_reasons", set())+++ ("enforce", "timeout", "attempts", "expected"),+ [+ (True, 300, 1, 310.0),+ (True, 300, 3, 910.0),+ (True, 300.5, 1, 310.5),+ (False, 300, 1, None),+ (True, 300, None, None),+ (True, None, 1, None),+ (True, 0, 1, None),+ (True, -1, 1, None),+ (True, "300", 1, None),+ (True, True, 1, None),+ ],+)+def test_llm_hard_deadline_seconds_only_extends_a_usable_timeout(+ monkeypatch: pytest.MonkeyPatch, enforce: bool, timeout: Any, attempts: int | None, expected: float | None+) -> None:+ _set_hard_deadline_settings(monkeypatch, enforce=enforce, grace=10.0)++ assert api_handler_factory._llm_hard_deadline_seconds(timeout, attempts) == expected+++ ("max_retries", "expected"),+ [(0, 1), (2, 3), (None, None), (-1, None), (True, None), ("2", None)],+)+def test_openai_client_attempts_reads_the_sdk_retry_budget(+ monkeypatch: pytest.MonkeyPatch, max_retries: Any, expected: int | None+) -> None:+ _set_hard_deadline_settings(monkeypatch, enforce=True, grace=10.0)+ client = SimpleNamespace(max_retries=max_retries)++ assert api_handler_factory._openai_client_attempts(client) == expected+ if expected is None:+ assert "client_max_retries" in api_handler_factory._hard_deadline_disabled_reasons+++async def test_hard_deadline_surfaces_as_retryable_from_the_public_call(monkeypatch: pytest.MonkeyPatch) -> None:+ provider_call_cancelled = asyncio.Event()++ async def _drip_forever(**kwargs: Any) -> Any:+ try:+ while True:+ await asyncio.sleep(0.01)+ except CancelledError:+ provider_call_cancelled.set()+ raise++ caller, _ = _openrouter_caller(monkeypatch, _drip_forever)+ _set_hard_deadline_settings(monkeypatch, enforce=True, grace=0.05)++ with pytest.raises(LLMProviderErrorRetryableTask):+ await caller.call(prompt="test prompt", prompt_name=EXTRACT_ACTION_PROMPT_NAME, timeout=0.05)++ assert provider_call_cancelled.is_set()+++async def test_hard_deadline_on_a_custom_openrouter_client_closes_it(monkeypatch: pytest.MonkeyPatch) -> None:+ async def _hang(**kwargs: Any) -> Any:+ await asyncio.sleep(60)++ caller, client = _openrouter_caller(monkeypatch, _hang, llm_key="CUSTOM_LLM_openrouter_deadline_test")+ _set_hard_deadline_settings(monkeypatch, enforce=True, grace=0.05)++ with pytest.raises(LLMProviderErrorRetryableTask):+ await caller.call(prompt="test prompt", prompt_name=EXTRACT_ACTION_PROMPT_NAME, timeout=0.05)++ client.close.assert_awaited_once()+ assert api_handler_factory.AsyncOpenAI.call_args.kwargs["max_retries"] == 0+++async def test_hard_deadline_scales_with_the_client_retry_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ """A client that retries twice may legitimately spend three timeouts, so 0.2s must survive a+ 0.1s timeout: the deadline covers 3 attempts, not one."""++ async def _slower_than_one_attempt(**kwargs: Any) -> Any:+ await asyncio.sleep(0.2)+ return SimpleNamespace(model_dump=lambda: {})++ caller, _ = _openrouter_caller(monkeypatch, _slower_than_one_attempt, max_retries=2)+ _set_hard_deadline_settings(monkeypatch, enforce=True, grace=0.0)++ await caller._dispatch_llm_call(messages=[], timeout=0.1)+++async def test_a_timeout_raised_inside_the_request_is_not_relabelled(monkeypatch: pytest.MonkeyPatch) -> None:+ async def _proxy_timeout(**kwargs: Any) -> Any:+ raise TimeoutError("connection to proxy timed out")++ caller, _ = _openrouter_caller(monkeypatch, _proxy_timeout)+ _set_hard_deadline_settings(monkeypatch, enforce=True, grace=10.0)++ with pytest.raises(TimeoutError, match="connection to proxy timed out") as raised:+ await caller._dispatch_llm_call(messages=[], timeout=300)++ assert not isinstance(raised.value, api_handler_factory.LLMProviderError)+++async def test_cancellation_landing_with_the_response_still_propagates(monkeypatch: pytest.MonkeyPatch) -> None:+ """A run-stop that arrives in the same tick the response resolves must still stop the run.+ Releasing the response and cancelling before the loop resumes the task pins that race."""+ provider_call_started = asyncio.Event()+ release_response = asyncio.Event()++ async def _responds_when_released(**kwargs: Any) -> Any:+ provider_call_started.set()+ await release_response.wait()+ return SimpleNamespace(model_dump=lambda: {})++ caller, _ = _openrouter_caller(monkeypatch, _responds_when_released)+ _set_hard_deadline_settings(monkeypatch, enforce=True, grace=10.0)++ dispatch = asyncio.create_task(caller._dispatch_llm_call(messages=[], timeout=300))+ await provider_call_started.wait()+ release_response.set()+ dispatch.cancel()++ with pytest.raises(CancelledError):+ await dispatch+++async def test_hard_deadline_does_not_convert_an_external_cancellation(monkeypatch: pytest.MonkeyPatch) -> None:+ provider_call_started = asyncio.Event()++ async def _hang(**kwargs: Any) -> Any:+ provider_call_started.set()+ await asyncio.sleep(60)++ caller, _ = _openrouter_caller(monkeypatch, _hang)+ _set_hard_deadline_settings(monkeypatch, enforce=True, grace=10.0)++ dispatch = asyncio.create_task(caller._dispatch_llm_call(messages=[], timeout=60))+ await provider_call_started.wait()+ dispatch.cancel()++ with pytest.raises(CancelledError):+ await dispatch+++async def test_hard_deadline_leaves_a_fast_call_untouched(monkeypatch: pytest.MonkeyPatch) -> None:+ completion = MagicMock()+ completion.model_dump.return_value = {"id": "chatcmpl-test"}+ create = AsyncMock(return_value=completion)+ caller, _ = _openrouter_caller(monkeypatch, create)+ _set_hard_deadline_settings(monkeypatch, enforce=True, grace=10.0)++ await caller._dispatch_llm_call(messages=[{"role": "user", "content": "test"}], timeout=30)++ assert create.await_args.kwargs["timeout"] == 30+ api_handler_factory.litellm.ModelResponse.assert_called_once_with(id="chatcmpl-test")+++async def test_hard_deadline_disabled_lets_a_slow_call_finish(monkeypatch: pytest.MonkeyPatch) -> None:+ completion = MagicMock()+ completion.model_dump.return_value = {}++ async def _slower_than_the_declared_timeout(**kwargs: Any) -> Any:+ await asyncio.sleep(0.05)+ return completion++ caller, _ = _openrouter_caller(monkeypatch, _slower_than_the_declared_timeout)+ _set_hard_deadline_settings(monkeypatch, enforce=False, grace=0.0)++ await caller._dispatch_llm_call(messages=[], timeout=0.001)++ completion.model_dump.assert_called_once()+++async def test_hard_deadline_disabled_skips_reading_the_client_retry_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ """The kill switch should fully silence the deadline machinery: it must not even read (and+ potentially warn about) the client's retry budget when the flag is off."""+ completion = MagicMock()+ completion.model_dump.return_value = {}+ create = AsyncMock(return_value=completion)+ caller, client = _openrouter_caller(monkeypatch, create)+ client.max_retries = -1 # malformed; would log if _openai_client_attempts ever inspected it+ _set_hard_deadline_settings(monkeypatch, enforce=False, grace=10.0)++ await caller._dispatch_llm_call(messages=[], timeout=30)++ assert api_handler_factory._hard_deadline_disabled_reasons == set()+++async def test_unparseable_response_body_is_retryable(monkeypatch: pytest.MonkeyPatch) -> None:+ async def _whitespace_only_200(**kwargs: Any) -> Any:+ raise json.JSONDecodeError("Expecting value", " ", 0)++ caller, _ = _openrouter_caller(monkeypatch, _whitespace_only_200)+ _set_hard_deadline_settings(monkeypatch, enforce=True, grace=10.0)++ with pytest.raises(LLMProviderErrorRetryableTask):+ await caller.call(prompt="test prompt", prompt_name=EXTRACT_ACTION_PROMPT_NAME)+++def _openai_rate_limit_error() -> Exception:+ request = httpx.Request("POST", "https://openrouter.ai/api/v1/chat/completions")+ return openai.RateLimitError("Too Many Requests", response=httpx.Response(429, request=request), body=None)+++def _litellm_rate_limit_error() -> Exception:+ return litellm.exceptions.RateLimitError("Too Many Requests", llm_provider="openrouter", model="example-model")+++ "make_rate_limit_error", [_openai_rate_limit_error, _litellm_rate_limit_error], ids=["openai", "litellm"]+)+async def test_a_rate_limited_custom_client_call_is_retryable(+ monkeypatch: pytest.MonkeyPatch, make_rate_limit_error: Any+) -> None:+ """max_retries=0 took away the SDK's silent retries on this path, so a 429 has to reach the+ step-level retry rather than failing the step outright."""++ async def _rate_limited(**kwargs: Any) -> Any:+ raise make_rate_limit_error()++ caller, _ = _openrouter_caller(monkeypatch, _rate_limited, llm_key="CUSTOM_LLM_openrouter_rate_limit_test")+ _set_hard_deadline_settings(monkeypatch, enforce=True, grace=10.0)++ with pytest.raises(LLMProviderErrorRetryableTask):+ await caller.call(prompt="test prompt", prompt_name=EXTRACT_ACTION_PROMPT_NAME)+++def test_json_error_body_length_tolerates_a_doc_less_error() -> None:+ assert api_handler_factory._json_error_body_length(json.JSONDecodeError("Expecting value", " ", 0)) == 2+ assert api_handler_factory._json_error_body_length(json.JSONDecodeError.__new__(json.JSONDecodeError)) is None++@pytest.mark.parametrize(("response", "expected"),[@@ -613,6 +890,32 @@ async def test_handler_persists_response_model_not_router_group(monkeypatch: pytassert captured_kwargs.get("last_llm_model") == "gemini-2.5-flash"+async def test_single_handler_maps_an_unparseable_body_to_retryable(monkeypatch: pytest.MonkeyPatch) -> None:+ llm_config = LLMConfig(+ model_name="vertex_ai/gemini-2.5-flash",+ required_env_vars=[],+ supports_vision=False,+ add_assistant_prefix=False,+ )+ monkeypatch.setattr(api_handler_factory.LLMConfigRegistry, "get_config", lambda _: llm_config)+ monkeypatch.setattr(api_handler_factory.LLMConfigRegistry, "is_router_config", lambda _: False)+ monkeypatch.setattr(api_handler_factory.skyvern_context, "current", lambda: None)+ monkeypatch.setattr(+ api_handler_factory, "llm_messages_builder", AsyncMock(return_value=[{"role": "user", "content": "test"}])+ )++ async def _whitespace_only_200(*args: Any, **kwargs: Any) -> Any:+ raise json.JSONDecodeError("Expecting value", " ", 0)++ monkeypatch.setattr(api_handler_factory.litellm, "acompletion", _whitespace_only_200)+ LLMAPIHandlerFactory._handler_cache.pop("TEST_UNPARSEABLE_SINGLE", None)++ handler = LLMAPIHandlerFactory.get_llm_api_handler("TEST_UNPARSEABLE_SINGLE")+ with pytest.raises(LLMProviderErrorRetryableTask):+ await handler(prompt="test prompt", prompt_name=EXTRACT_ACTION_PROMPT_NAME)++def test_aiohttp_transport_disabled_for_per_request_timeouts() -> None:"""Importing the LLM package disables litellm's aiohttp transport so per-request `timeout` is honored."""assert litellm.disable_aiohttp_transport is True@@ -1303,6 +1606,33 @@ async def test_router_acompletion_does_not_pass_timeout_kwarg(monkeypatch: pytes)+async def test_router_handler_reports_an_unparseable_body_as_such(monkeypatch: pytest.MonkeyPatch) -> None:+ """The router ladder already treated this as retryable through its ValueError branch, which+ logs every such failure as a token limit. Keep the classification, name the real cause."""++ class _UnparseableRouter:+ def __init__(self, **kwargs: Any) -> None:+ pass++ async def acompletion(self, *, model: str, messages: Any, **kwargs: Any) -> Any:+ raise json.JSONDecodeError("Expecting value", " ", 0)++ monkeypatch.setattr(api_handler_factory.litellm, "Router", _UnparseableRouter)++ config = _make_three_tier_router_config(fallback_groups=[])+ _stub_for_router_test(monkeypatch, llm_key="TEST_UNPARSEABLE_ROUTER", config=config)+ logger = DummyLogger()+ monkeypatch.setattr(api_handler_factory, "LOG", logger)++ handler = LLMAPIHandlerFactory.get_llm_api_handler_with_router("TEST_UNPARSEABLE_ROUTER")+ with pytest.raises(LLMProviderErrorRetryableTask):+ await handler(prompt="test prompt", prompt_name=EXTRACT_ACTION_PROMPT_NAME)++ assert "LLM response body was not parseable JSON" in [event for event, _ in logger.warnings]+ assert "LLM token limit exceeded" not in [event for event, _ in logger.exceptions]++@pytest.mark.asyncioasync def test_router_retries_content_filter_on_first_non_gemini_fallback(monkeypatch: pytest.MonkeyPatch) -> None:"""Gemini's non-configurable content filter blocks a PII-heavy prompt, returning a *valid*