diff --git a/haystack/utils/jinja2_extensions.py b/haystack/utils/jinja2_extensions.py index aa49ab844e1..ce129760570 100644 --- a/haystack/utils/jinja2_extensions.py +++ b/haystack/utils/jinja2_extensions.py @@ -2,6 +2,7 @@ # # SPDX-License-Identifier: Apache-2.0 +from collections.abc import Sequence from typing import Any from jinja2 import Environment, meta, nodes @@ -103,6 +104,23 @@ def parse(self, parser: Any) -> nodes.Node | list[nodes.Node]: return nodes.Output([call_method], lineno=lineno) +def _assigned_names(target: nodes.Node) -> set[str]: + """The names an assignment target binds: one name, or the items of a list or tuple.""" + if isinstance(target, nodes.Name): + return {target.name} + if isinstance(target, (nodes.List, nodes.Tuple)): + return {item.name for item in target.items if isinstance(item, nodes.Name)} + + return set() + + +def _read_names(parts: nodes.Node | Sequence[nodes.Node]) -> set[str]: + """Every name `parts` reads, so an assignment that mentions a name is known to consume it.""" + children = [parts] if isinstance(parts, nodes.Node) else parts + + return {name.name for child in children for name in child.find_all(nodes.Name) if name.ctx == "load"} + + def _collect_assigned_variables(ast: nodes.Template) -> set[str]: """ Extract variables assigned within the Jinja2 template AST. @@ -120,12 +138,13 @@ def _collect_assigned_variables(ast: nodes.Template) -> set[str]: ] for node in assignments: - if isinstance(node.target, nodes.Name): - assigned_variables.add(node.target.name) - elif isinstance(node.target, (nodes.List, nodes.Tuple)): - for name_node in node.target.items: - if isinstance(name_node, nodes.Name): - assigned_variables.add(name_node.name) + targets = _assigned_names(node.target) + + # A name the assignment itself reads is the caller's, not the template's: + # `{% set quantity = quantity | default(1) %}` exists to default a value the + # caller supplies, so reporting `quantity` as assigned removes it from the + # variables the component asks for and the default always wins (#13770). + assigned_variables |= targets - _read_names(node.node if isinstance(node, nodes.Assign) else node.body) return assigned_variables diff --git a/test/components/builders/test_chat_prompt_builder.py b/test/components/builders/test_chat_prompt_builder.py index 50c1313c9f8..8490443d610 100644 --- a/test/components/builders/test_chat_prompt_builder.py +++ b/test/components/builders/test_chat_prompt_builder.py @@ -20,6 +20,27 @@ class TestChatPromptBuilder: + def test_a_set_that_reads_its_own_name_keeps_that_variable_required(self): + """`{% set quantity = quantity | default(1) %}` defaults a value the caller supplies.""" + builder = ChatPromptBuilder( + template=[ChatMessage.from_user("{% set quantity = quantity | default(1) %}Order {{ quantity }} cartons.")] + ) + + inputs = builder.__haystack_input__._sockets_dict # type: ignore[attr-defined] + + assert "quantity" in inputs + assert builder.variables == ["quantity"] + + def test_a_set_that_does_not_read_its_own_name_is_still_the_templates(self): + """`{% set quantity = 12 %}` is the template's own value, not a caller's.""" + builder = ChatPromptBuilder( + template=[ChatMessage.from_user("{% set quantity = 12 %}Order {{ quantity }} cartons.")] + ) + + inputs = builder.__haystack_input__._sockets_dict # type: ignore[attr-defined] + + assert "quantity" not in inputs + def test_init(self): builder = ChatPromptBuilder( template=[