Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Keep each run's LLM choices in its own context instead of the shared app (SKY-16970) (#8908)
Shuchang Zheng75665582ee6c
diff --git a/skyvern/forge/__init__.py b/skyvern/forge/__init__.pyindex eaec27f99..0c6ac30a5 100644--- a/skyvern/forge/__init__.py+++ b/skyvern/forge/__init__.py@@ -1,11 +1,20 @@from __future__ import annotationsimport typing+from collections.abc import Mapping+from contextvars import ContextVar, Token+from types import MappingProxyTypefrom typing import Anyif typing.TYPE_CHECKING:from skyvern.forge.forge_app import ForgeApp+# A run's own values for app attributes, such as the LLM handlers its experiments pick. A worker running several+# activities in one process shares the app, so a run's choices live in its context, where reads look first.+_RUN_SCOPED_ATTRIBUTES: ContextVar[Mapping[str, Any]] = ContextVar(+ "run_scoped_app_attributes", default=MappingProxyType({})+)+class AppHolder:def __init__(self) -> None:@@ -15,6 +24,9 @@ class AppHolder:object.__setattr__(self, "_inst", inst)def __getattr__(self, name: str) -> Any:+ scoped = _RUN_SCOPED_ATTRIBUTES.get()+ if name in scoped:+ return scoped[name]inst = object.__getattribute__(self, "_inst")if inst is None:raise RuntimeError("ForgeApp is not initialized. Call start_forge_app() before accessing app properties.")@@ -37,3 +49,18 @@ else:def set_force_app_instance(inst: ForgeApp) -> None:app.set_app(inst) # type: ignore+++def set_run_scoped_app_attribute(name: str, value: Any) -> None:+ """Give the current run, meaning this task and the tasks it starts afterwards, its own value of an app attribute."""+ _RUN_SCOPED_ATTRIBUTES.set(MappingProxyType({**_RUN_SCOPED_ATTRIBUTES.get(), name: value}))+++def begin_run_scoped_app_attributes() -> Token[Mapping[str, Any]]:+ """Start a run with no run-scoped app values; pass the token to end_run_scoped_app_attributes when it ends."""+ return _RUN_SCOPED_ATTRIBUTES.set(MappingProxyType({}))+++def end_run_scoped_app_attributes(token: Token[Mapping[str, Any]]) -> None:+ """Drop the run's values, restoring those of any run that encloses it on the same task."""+ _RUN_SCOPED_ATTRIBUTES.reset(token)diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 48fdc61ba..9b5a59a6d 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -8494,8 +8494,9 @@ class ForgeAgent:are mostly used by scripts/tests. When no override exists, evaluate the PostHog experimentonce per context and cache the result on the context to avoid repeated lookups."""- if LLMAPIHandlerFactory._prompt_caching_settings is not None:- return LLMAPIHandlerFactory._prompt_caching_settings+ explicit_settings = LLMAPIHandlerFactory.prompt_caching_settings()+ if explicit_settings is not None:+ return explicit_settingsif context.prompt_caching_settings is not None:return context.prompt_caching_settingsdiff --git a/skyvern/forge/sdk/api/llm/api_handler_factory.py b/skyvern/forge/sdk/api/llm/api_handler_factory.pyindex 93faaddcc..5ef52754f 100644--- a/skyvern/forge/sdk/api/llm/api_handler_factory.py+++ b/skyvern/forge/sdk/api/llm/api_handler_factory.py@@ -8,6 +8,7 @@ import timeimport warningsfrom asyncio import CancelledErrorfrom collections.abc import Collection+from contextvars import ContextVar, Tokenfrom json import JSONDecodeErrorfrom types import MappingProxyTypefrom typing import Any, AsyncIterator, Literal, Protocol, runtime_checkable@@ -1080,6 +1081,16 @@ def _convert_allowed_fails_policy(policy: LLMAllowedFailsPolicy | None) -> Allow# can validate against the same set instead of duplicating the values.VALID_GEMINI_3_REASONING_EFFORTS: tuple[str, ...] = ("minimal", "low", "medium", "high")+# A run's LLM experiment settings. A worker running several activities in one process shares the factory, so each run+# keeps its own values in its context rather than on the class.+_THINKING_BUDGET_SETTINGS: ContextVar[dict[str, int] | None] = ContextVar("llm_thinking_budget_settings", default=None)+_PROMPT_CACHING_SETTINGS: ContextVar[dict[str, bool] | None] = ContextVar("llm_prompt_caching_settings", default=None)+# When set, Gemini 3.x calls use `reasoning_effort=<value>` (mapping to `thinkingLevel` in Vertex) instead of the legacy+# `thinking={budget_tokens:N}` payload, which litellm silently drops for Gemini 3 (SKY-9785).+_GEMINI_3_REASONING_EFFORT_OVERRIDE: ContextVar[str | None] = ContextVar(+ "llm_gemini_3_reasoning_effort_override", default=None+)+def _build_litellm_router(llm_config: LLMRouterConfig) -> litellm.Router:"""Build a litellm.Router from a router config.@@ -1161,13 +1172,6 @@ class LLMAPIHandlerFactory:_custom_handlers: dict[str, LLMAPIHandler] = {}_handler_cache: dict[str, tuple[LLMConfig, LLMAPIHandler]] = {}_router_handler_cache: dict[str, LLMAPIHandler] = {}- _thinking_budget_settings: dict[str, int] | None = None- _prompt_caching_settings: dict[str, bool] | None = None- # When set, Gemini 3.x calls use `reasoning_effort=<value>` (mapping to- # `thinkingLevel` in Vertex) instead of the legacy `thinking={budget_tokens:N}`- # payload — which litellm silently drops for Gemini 3, leaving the model at- # its default HIGH thinking level (SKY-9785).- _gemini_3_reasoning_effort_override: str | None = None@staticmethoddef _strip_static_prompt_from_messages(messages: list[dict[str, Any]], static_prompt: str) -> bool:@@ -1692,7 +1696,7 @@ class LLMAPIHandlerFactory:# into `parameters`. Without this ordering, the guard would fire and the# override would silently skip direct Gemini 3 configs (task/workflow-level# model overrides that bypass the router).- override = LLMAPIHandlerFactory._gemini_3_reasoning_effort_override+ override = _GEMINI_3_REASONING_EFFORT_OVERRIDE.get()if override and LLMAPIHandlerFactory._is_gemini_3_model(llm_config):parameters["reasoning_effort"] = override# litellm raises 400 if both reasoning_effort and thinking_budget land@@ -2003,11 +2007,9 @@ class LLMAPIHandlerFactory:parameters = LLMAPIHandlerFactory.get_api_parameters(llm_config)# Apply thinking budget optimization if settings are available- if (- LLMAPIHandlerFactory._thinking_budget_settings- and prompt_name in LLMAPIHandlerFactory._thinking_budget_settings- ):- new_budget = LLMAPIHandlerFactory._thinking_budget_settings[prompt_name]+ thinking_budget_settings = _THINKING_BUDGET_SETTINGS.get()+ if thinking_budget_settings and prompt_name in thinking_budget_settings:+ new_budget = thinking_budget_settings[prompt_name]LLMAPIHandlerFactory._apply_thinking_budget_optimization(parameters, new_budget, llm_config, prompt_name)@@ -2870,13 +2872,11 @@ class LLMAPIHandlerFactory:# nested dict retained in llm_config.litellm_params via the shallow merge above). SKY-13345.customer_owns_thinking = LLMAPIHandlerFactory._custom_llm_owns_thinking(llm_key, active_parameters)# Apply thinking budget optimization if settings are available+ thinking_budget_settings = _THINKING_BUDGET_SETTINGS.get()if customer_owns_thinking:pass- elif (- LLMAPIHandlerFactory._thinking_budget_settings- and prompt_name in LLMAPIHandlerFactory._thinking_budget_settings- ):- new_budget = LLMAPIHandlerFactory._thinking_budget_settings[prompt_name]+ elif thinking_budget_settings and prompt_name in thinking_budget_settings:+ new_budget = thinking_budget_settings[prompt_name]LLMAPIHandlerFactory._apply_thinking_budget_optimization(active_parameters, new_budget, llm_config, prompt_name)@@ -3517,14 +3517,46 @@ class LLMAPIHandlerFactory:@classmethoddef set_thinking_budget_settings(cls, settings: dict[str, int] | None) -> None:"""Set thinking budget optimization settings for the current task/workflow."""- cls._thinking_budget_settings = settings+ _THINKING_BUDGET_SETTINGS.set(settings)if settings:LOG.info("Thinking budget optimization settings applied", settings=settings)+ @staticmethod+ def begin_run_settings() -> tuple[Token[Any], ...]:+ """Start a run with no thinking budget, prompt caching or Gemini 3 effort settings; see end_run_settings."""+ return (+ _THINKING_BUDGET_SETTINGS.set(None),+ _PROMPT_CACHING_SETTINGS.set(None),+ _GEMINI_3_REASONING_EFFORT_OVERRIDE.set(None),+ )++ @staticmethod+ def end_run_settings(tokens: tuple[Token[Any], ...]) -> None:+ """Drop the run's settings, restoring those of any run that encloses it on the same task."""+ thinking_budget, prompt_caching, gemini_3_effort = tokens+ _GEMINI_3_REASONING_EFFORT_OVERRIDE.reset(gemini_3_effort)+ _PROMPT_CACHING_SETTINGS.reset(prompt_caching)+ _THINKING_BUDGET_SETTINGS.reset(thinking_budget)++ @staticmethod+ def thinking_budget_settings() -> dict[str, int] | None:+ """The current run's thinking budget settings, if any were set."""+ return _THINKING_BUDGET_SETTINGS.get()++ @staticmethod+ def gemini_3_reasoning_effort_override() -> str | None:+ """The current run's Gemini 3 reasoning_effort override, if one was set."""+ return _GEMINI_3_REASONING_EFFORT_OVERRIDE.get()++ @staticmethod+ def prompt_caching_settings() -> dict[str, bool] | None:+ """The current run's prompt caching settings, if any were set."""+ return _PROMPT_CACHING_SETTINGS.get()+@classmethoddef set_prompt_caching_settings(cls, settings: dict[str, bool] | None) -> None:"""Set prompt caching optimization settings for the current task/workflow."""- cls._prompt_caching_settings = settings+ _PROMPT_CACHING_SETTINGS.set(settings)if settings:LOG.info("Prompt caching optimization settings applied", settings=settings)@@ -3537,7 +3569,7 @@ class LLMAPIHandlerFactory:and logged."""if not value:- cls._gemini_3_reasoning_effort_override = None+ _GEMINI_3_REASONING_EFFORT_OVERRIDE.set(None)returnnormalized = value.strip().lower() if isinstance(value, str) else Noneif normalized not in VALID_GEMINI_3_REASONING_EFFORTS:@@ -3546,9 +3578,9 @@ class LLMAPIHandlerFactory:value=value,valid_values=list(VALID_GEMINI_3_REASONING_EFFORTS),)- cls._gemini_3_reasoning_effort_override = None+ _GEMINI_3_REASONING_EFFORT_OVERRIDE.set(None)return- cls._gemini_3_reasoning_effort_override = normalized+ _GEMINI_3_REASONING_EFFORT_OVERRIDE.set(normalized)LOG.info("Gemini 3 reasoning_effort override applied", value=normalized)diff --git a/tests/unit/test_api_handler_factory.py b/tests/unit/test_api_handler_factory.pyindex 3a7e6dc8a..2bcca95a0 100644--- a/tests/unit/test_api_handler_factory.py+++ b/tests/unit/test_api_handler_factory.py@@ -1746,12 +1746,12 @@ class TestGemini3ReasoningEffortExperiment:@pytest.mark.parametrize("value", ["minimal", "low", "medium", "high", "MEDIUM", " low "])def test_set_gemini_3_reasoning_effort_override_accepts_valid_values(self, value: str) -> None:LLMAPIHandlerFactory.set_gemini_3_reasoning_effort_override(value)- assert LLMAPIHandlerFactory._gemini_3_reasoning_effort_override == value.strip().lower()+ assert LLMAPIHandlerFactory.gemini_3_reasoning_effort_override() == value.strip().lower()@pytest.mark.parametrize("value", ["disable", "off", "high-er", 1024])def test_set_gemini_3_reasoning_effort_override_rejects_invalid_values(self, value: Any) -> None:LLMAPIHandlerFactory.set_gemini_3_reasoning_effort_override(value)- assert LLMAPIHandlerFactory._gemini_3_reasoning_effort_override is None+ assert LLMAPIHandlerFactory.gemini_3_reasoning_effort_override() is Nonedef test_apply_gemini_thinking_optimization_overrides_when_thinking_level_pre_merged(self) -> None:"""Single-handler path (api_handler_factory.py:1402-1404) merges