Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Fix conditional evaluation for empty parameters (#SKY-8073) (#4907)
Celal Zamanoğlu4467a377921a
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex f772bc508..28e30772d 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -5427,6 +5427,83 @@ def _parse_single_evaluation(return (bool_result, rendered_expression)+# Pattern to find Jinja template blocks like {{ variable_name }}+_JINJA_BLOCK_RE = re.compile(r"\{\{(.*?)\}\}")+# Marker inserted into rendered expressions when a Jinja variable resolved to+# an empty/whitespace-only value. The LLM uses this to reason about emptiness.+_EMPTY_VALUE_MARKER = "(empty value)"+++def _make_empty_params_explicit(+ original_expression: str,+ rendered_expression: str,+) -> tuple[str, bool]:+ """+ Detect Jinja template variables that resolved to empty values and replace+ the empty gaps with explicit ``(empty value)`` markers.++ When ``{{test_parameter}}`` resolves to ``""``, the rendered expression becomes+ malformed (e.g., ``"if is not empty"``). This function detects such cases by+ comparing the *original* expression (with ``{{ }}`` blocks) against the+ *rendered* expression and rebuilds it with clear markers so the LLM can+ evaluate the condition correctly.++ Returns:+ ``(patched_expression, was_patched)``+ """+ if not original_expression or "{{" not in original_expression:+ return rendered_expression, False++ # Split the original expression into alternating [static, var, static, var, ...] parts.+ parts = _JINJA_BLOCK_RE.split(original_expression)+ if len(parts) <= 1:+ return rendered_expression, False++ # Extract static parts (even indices) and build a regex that captures what+ # each Jinja block rendered to by using the static text as anchors.+ static_parts = [parts[i] for i in range(0, len(parts), 2)]+ num_vars = len(parts) // 2++ # When two Jinja variables are adjacent (e.g. "{{a}}{{b}}") the interior+ # static separator is an empty string and the non-greedy regex cannot+ # reliably attribute rendered text to the correct variable. Bail out.+ if num_vars > 1 and any(static == "" for static in static_parts[1:-1]):+ return rendered_expression, False++ # NOTE: if a rendered value happens to contain the same text as a static+ # anchor the regex may split on the wrong occurrence. This is extremely+ # unlikely in user-authored conditional expressions and the worst-case+ # outcome is an unnecessary "(empty value)" marker, which still beats the+ # invisible empty-string that caused SKY-8073.++ regex_fragments: list[str] = []+ for i, static in enumerate(static_parts):+ regex_fragments.append(re.escape(static))+ if i < num_vars:+ regex_fragments.append("(.*?)")++ match = re.match("^" + "".join(regex_fragments) + "$", rendered_expression, re.DOTALL)+ if not match:+ return rendered_expression, False++ rendered_values = match.groups()+ has_empty = any(not v.strip() for v in rendered_values)+ if not has_empty:+ return rendered_expression, False++ # Rebuild the expression, replacing empty rendered values with an explicit marker.+ result_parts: list[str] = []+ for i, static in enumerate(static_parts):+ result_parts.append(static)+ if i < len(rendered_values):+ if not rendered_values[i].strip():+ result_parts.append(_EMPTY_VALUE_MARKER)+ else:+ result_parts.append(rendered_values[i])++ return "".join(result_parts), True++class BranchCondition(BaseModel):"""Represents a single conditional branch edge within a ConditionalBlock."""@@ -5557,6 +5634,21 @@ class ConditionalBlock(Block):# Rendering failed, so this expression is effectively unresolved and must# take the ExtractionBlock path (with context) instead of direct LLM mode.has_any_pure_natlang = True+ else:+ # When a Jinja variable resolves to an empty string the rendered+ # expression becomes malformed (e.g. "if is not empty") and the+ # LLM cannot reason about emptiness correctly. Replace empty gaps+ # with an explicit "(empty value)" marker so the intent is clear.+ rendered_expression, was_patched = _make_empty_params_explicit(expression, rendered_expression)+ if was_patched:+ LOG.info(+ "Conditional branch expression patched for empty parameter(s)",+ workflow_run_id=workflow_run_id,+ block_label=self.label,+ branch_index=idx,+ original_expression=expression,+ patched_expression=rendered_expression,+ )else:rendered_expression = expressionhas_any_pure_natlang = Truediff --git a/tests/unit/workflow/test_conditional_branch_evaluation.py b/tests/unit/workflow/test_conditional_branch_evaluation.pyindex b7b7960dd..592c30ec7 100644--- a/tests/unit/workflow/test_conditional_branch_evaluation.py+++ b/tests/unit/workflow/test_conditional_branch_evaluation.py@@ -11,6 +11,7 @@ from skyvern.forge.sdk.workflow.models.block import (BranchEvaluationContext,ConditionalBlock,PromptBranchCriteria,+ _make_empty_params_explicit,)from skyvern.forge.sdk.workflow.models.parameter import OutputParameterfrom skyvern.schemas.workflows import BlockResult@@ -234,3 +235,165 @@ async def test_jinja_render_failure_falls_back_to_extraction_block() -> None:assert mock_extraction.execute.call_args.kwargs["browser_session_id"] == "bs_test"mock_llm_handler.assert_not_called()evaluation_context.build_llm_safe_context_snapshot.assert_called_once() # type: ignore[attr-defined]+++# ---------------------------------------------------------------------------+# Tests for _make_empty_params_explicit (SKY-8073)+# ---------------------------------------------------------------------------+++class TestMakeEmptyParamsExplicit:+ """Unit tests for _make_empty_params_explicit helper."""++ def test_empty_param_is_patched(self) -> None:+ """When a single parameter resolves to empty string, it should be replaced with (empty value)."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="if {{test_parameter}} is not empty",+ rendered_expression="if is not empty",+ )+ assert was_patched is True+ assert patched == "if (empty value) is not empty"++ def test_non_empty_param_is_not_patched(self) -> None:+ """Non-empty parameter values should pass through unchanged."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="if {{test_parameter}} is not empty",+ rendered_expression="if hello is not empty",+ )+ assert was_patched is False+ assert patched == "if hello is not empty"++ def test_no_jinja_blocks(self) -> None:+ """Expressions without Jinja blocks should pass through unchanged."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="user selected premium plan",+ rendered_expression="user selected premium plan",+ )+ assert was_patched is False+ assert patched == "user selected premium plan"++ def test_multiple_params_one_empty(self) -> None:+ """When one of multiple parameters is empty, only that one should be patched."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="{{a}} equals {{b}}",+ rendered_expression=" equals hello",+ )+ assert was_patched is True+ assert patched == "(empty value) equals hello"++ def test_multiple_params_both_empty(self) -> None:+ """When all parameters are empty, all should be patched."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="{{a}} equals {{b}}",+ rendered_expression=" equals ",+ )+ assert was_patched is True+ assert patched == "(empty value) equals (empty value)"++ def test_whitespace_only_param_is_patched(self) -> None:+ """A parameter that resolves to whitespace-only should be treated as empty."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="if {{test_parameter}} is not empty",+ rendered_expression="if is not empty",+ )+ assert was_patched is True+ assert patched == "if (empty value) is not empty"++ def test_empty_original_expression(self) -> None:+ """Empty original expression should pass through."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="",+ rendered_expression="",+ )+ assert was_patched is False++ def test_adjacent_variables_are_skipped(self) -> None:+ """Adjacent Jinja variables (no separator) cannot be reliably split, so skip patching."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="{{a}}{{b}}",+ rendered_expression="helloworld",+ )+ assert was_patched is False+ assert patched == "helloworld"++ def test_param_at_end_of_expression(self) -> None:+ """Parameter at the end of an expression should be handled correctly."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="check if empty: {{param}}",+ rendered_expression="check if empty: ",+ )+ assert was_patched is True+ assert patched == "check if empty: (empty value)"++ def test_single_bare_variable_empty(self) -> None:+ """Entire expression is one variable that resolved to empty string."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="{{a}}",+ rendered_expression="",+ )+ assert was_patched is True+ assert patched == "(empty value)"++ def test_rendered_value_containing_static_anchor(self) -> None:+ """When a rendered value contains static anchor text, regex may mis-split.+ Verify we don't falsely detect an empty parameter."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="{{a}} equals {{b}}",+ rendered_expression="x equals y equals z",+ )+ assert was_patched is False+ assert patched == "x equals y equals z"++ def test_multiline_rendered_value_passes_through(self) -> None:+ """Multiline rendered values (re.DOTALL path) should not be falsely patched."""+ patched, was_patched = _make_empty_params_explicit(+ original_expression="if {{data}} is valid",+ rendered_expression="if line1\nline2 is valid",+ )+ assert was_patched is False+ assert patched == "if line1\nline2 is valid"+++async def test_empty_param_produces_explicit_marker_in_prompt_evaluation() -> None:+ """Integration test: when a parameter resolves to empty string, the rendered+ expression sent to the LLM should contain '(empty value)' so the LLM can+ correctly evaluate the condition (SKY-8073)."""+ block = _conditional_block()+ branch = BranchCondition(+ criteria=PromptBranchCriteria(expression="if {{test_parameter}} is not empty"),+ next_block_label="not_empty_branch",+ )++ evaluation_context = BranchEvaluationContext(+ workflow_run_context=None,+ template_renderer=lambda expr: expr.replace("{{test_parameter}}", ""),+ )+ evaluation_context.build_llm_safe_context_snapshot = MagicMock(return_value={"test_parameter": ""}) # type: ignore[method-assign]++ with (+ patch("skyvern.forge.sdk.workflow.models.block.prompt_engine.load_prompt", return_value="goal") as mock_prompt,+ patch("skyvern.forge.sdk.workflow.models.block.ExtractionBlock") as mock_extraction_cls,+ ):+ mock_extraction = MagicMock()+ mock_extraction.execute = AsyncMock(+ return_value=_extraction_result(+ block.output_parameter,+ [{"reasoning": "empty value is not empty -> false", "result": False}],+ )+ )+ mock_extraction_cls.return_value = mock_extraction++ results, rendered_expressions, _, _ = await block._evaluate_prompt_branches(+ branches=[branch],+ evaluation_context=evaluation_context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="org_test",+ )++ assert results == [False]+ # The rendered expression should contain the explicit marker, not a bare gap+ assert rendered_expressions == ["if (empty value) is not empty"]+ # The prompt should be loaded with the patched expression+ assert mock_prompt.call_args.kwargs["conditions"] == ["if (empty value) is not empty"]