Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Improve the positional args error message for dspy.Predict (#8152)

Chen Qian85a91264a7e7
diff --git a/dspy/predict/predict.py b/dspy/predict/predict.py
index b4a94a367..9f78ca804 100644
--- a/dspy/predict/predict.py
+++ b/dspy/predict/predict.py
@@ -70,23 +70,24 @@ class Predict(Module, Parameter):
return self
+ def _get_positional_args_error_message(self):
+ input_fields = list(self.signature.input_fields.keys())
+ return (
+ "Positional arguments are not allowed when calling `dspy.Predict`, must use keyword arguments "
+ f"that match your signature input fields: '{', '.join(input_fields)}'. For example: "
+ f"`predict({input_fields[0]}=input_value, ...)`."
+ )
+
def __call__(self, *args, **kwargs):
if args:
- raise ValueError(
- "Positional arguments are not allowed when calling `dspy.Predict`, must use keyword arguments "
- "that match your signature input fields. For example: "
- "dspy.Predict('question -> answer')(question='What is the capital of France?')"
- )
+ raise ValueError(self._get_positional_args_error_message())
return super().__call__(**kwargs)
async def acall(self, *args, **kwargs):
if args:
- raise ValueError(
- "Positional arguments are not allowed when calling `dspy.Predict`, must use keyword arguments "
- "that match your signature input fields. For example: "
- "dspy.Predict('question -> answer').acall(question='What is the capital of France?')"
- )
+ raise ValueError(self._get_positional_args_error_message())
+
return await super().acall(**kwargs)
def _forward_preprocess(self, **kwargs):
diff --git a/tests/predict/test_predict.py b/tests/predict/test_predict.py
index c60526068..685f55826 100644
--- a/tests/predict/test_predict.py
+++ b/tests/predict/test_predict.py
@@ -511,8 +511,9 @@ def test_positional_arguments():
program = Predict("question -> answer")
with pytest.raises(ValueError) as e:
program("What is the capital of France?")
- assert "Positional arguments are not allowed when calling `dspy.Predict`, must use keyword arguments" in str(
- e.value
+ assert str(e.value) == (
+ "Positional arguments are not allowed when calling `dspy.Predict`, must use keyword arguments that match "
+ "your signature input fields: 'question'. For example: `predict(question=input_value, ...)`."
)