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
31 changes: 25 additions & 6 deletions haystack/utils/jinja2_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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

Expand Down
21 changes: 21 additions & 0 deletions test/components/builders/test_chat_prompt_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=[
Expand Down