core: prompt variable error msg (#25787)

This commit is contained in:
Erick Friis 2024-08-28 15:54:00 -07:00 committed by GitHub
parent ff168aaec0
commit c8b8335b82
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 20 additions and 1 deletions

View File

@ -142,11 +142,18 @@ class BasePromptTemplate(
)
missing = set(self.input_variables).difference(inner_input)
if missing:
raise KeyError(
msg = (
f"Input to {self.__class__.__name__} is missing variables {missing}. "
f" Expected: {self.input_variables}"
f" Received: {list(inner_input.keys())}"
)
example_key = missing.pop()
msg += (
f"\nNote: if you intended {{{example_key}}} to be part of the string"
" and not a variable, please escape it with double curly braces like: "
f"'{{{{{example_key}}}}}'."
)
raise KeyError(msg)
return inner_input
def _format_prompt_with_error_handling(self, inner_input: Dict) -> PromptValue:

View File

@ -702,3 +702,15 @@ def test_prompt_falsy_vars(
expected if not isinstance(expected, dict) else expected[template_format]
)
assert result.to_string() == expected_output
def test_prompt_missing_vars_error() -> None:
prompt = PromptTemplate.from_template("This is a {foo} {goingtobemissing} test.")
with pytest.raises(KeyError) as e:
prompt.invoke({"foo": "bar"})
# Check that the error message contains the missing variable
assert "{'goingtobemissing'}" in str(e.value.args[0])
# Check helper text has right number of braces
assert "'{{goingtobemissing}}'" in str(e.value.args[0])