Skip to content

Commit 136b7e0

Browse files
committed
fix: prompt-builder - jinja2 template set vars still shows required
1 parent 34aa66e commit 136b7e0

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

haystack/components/builders/prompt_builder.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from typing import Any, Literal, Optional, Union
66

7-
from jinja2 import meta
7+
from jinja2 import meta, nodes
88
from jinja2.sandbox import SandboxedEnvironment
99

1010
from haystack import component, default_to_dict, logging
@@ -178,7 +178,13 @@ def __init__(
178178
# infer variables from template
179179
ast = self._env.parse(template)
180180
template_variables = meta.find_undeclared_variables(ast)
181-
variables = list(template_variables)
181+
182+
assigned_variables = set()
183+
for node in ast.find_all((nodes.Assign, nodes.For)):
184+
if hasattr(node.target, "name"):
185+
assigned_variables.add(node.target.name)
186+
187+
variables = list(template_variables - assigned_variables)
182188
variables = variables or []
183189
self.variables = variables
184190

test/components/builders/test_prompt_builder.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,3 +337,25 @@ def test_warning_no_required_variables(self, caplog):
337337
with caplog.at_level(logging.WARNING):
338338
_ = PromptBuilder(template="This is a {{ variable }}")
339339
assert "but `required_variables` is not set." in caplog.text
340+
341+
def test_template_assigned_variables_from_required_inputs(self) -> None:
342+
template = """{% if existing_documents is not none %}
343+
{% set existing_doc_len = existing_documents|length %}
344+
{% else %}
345+
{% set existing_doc_len = 0 %}
346+
{% endif %}
347+
{% for doc in docs %}
348+
<document reference="{{loop.index + existing_doc_len}}">
349+
{{ doc.content }}
350+
</document>
351+
{% endfor %}
352+
"""
353+
354+
builder = PromptBuilder(template=template, required_variables="*")
355+
docs = [Document(content="Doc 1"), Document(content="Doc 2")]
356+
357+
res = builder.run(docs=docs, existing_documents=None)
358+
359+
assert "<document reference=" in res["prompt"]
360+
assert "Doc 1" in res["prompt"]
361+
assert "Doc 2" in res["prompt"]

0 commit comments

Comments
 (0)