Skip to content

The agent engineering platform.

Fixing empty input variable crashing `PromptTemplate` validations (#14314)

James Braza8b0060184d65
diff --git a/libs/core/langchain_core/prompts/string.py b/libs/core/langchain_core/prompts/string.py
index d61660f2b8..e454b8280a 100644
--- a/libs/core/langchain_core/prompts/string.py
+++ b/libs/core/langchain_core/prompts/string.py
@@ -106,20 +106,20 @@ def check_valid_template(
Raises:
ValueError: If the template format is not supported.
"""
- if template_format not in DEFAULT_FORMATTER_MAPPING:
- valid_formats = list(DEFAULT_FORMATTER_MAPPING)
- raise ValueError(
- f"Invalid template format. Got `{template_format}`;"
- f" should be one of {valid_formats}"
- )
try:
validator_func = DEFAULT_VALIDATOR_MAPPING[template_format]
+ except KeyError as exc:
+ raise ValueError(
+ f"Invalid template format {template_format!r}, should be one of"
+ f" {list(DEFAULT_FORMATTER_MAPPING)}."
+ ) from exc
+ try:
validator_func(template, input_variables)
- except KeyError as e:
+ except (KeyError, IndexError) as exc:
raise ValueError(
- "Invalid prompt schema; check for mismatched or missing input parameters. "
- + str(e)
- )
+ "Invalid prompt schema; check for mismatched or missing input parameters"
+ f" from {input_variables}."
+ ) from exc
def get_template_variables(template: str, template_format: str) -> List[str]:
diff --git a/libs/core/tests/unit_tests/prompts/test_prompt.py b/libs/core/tests/unit_tests/prompts/test_prompt.py
index f931dd80bc..1b63b8859e 100644
--- a/libs/core/tests/unit_tests/prompts/test_prompt.py
+++ b/libs/core/tests/unit_tests/prompts/test_prompt.py
@@ -47,6 +47,12 @@ def test_prompt_missing_input_variables() -> None:
).input_variables == ["foo"]
+def test_prompt_empty_input_variable() -> None:
+ """Test error is raised when empty string input variable."""
+ with pytest.raises(ValueError):
+ PromptTemplate(input_variables=[""], template="{}", validate_template=True)
+
+
def test_prompt_extra_input_variables() -> None:
"""Test error is raised when there are too many input variables."""
template = "This is a {foo} test."