DSPy: The framework for programming—not prompting—language models
Python
Provide language to dspy.Code (#8519)
Chen Qiancacc02e68183
diff --git a/dspy/adapters/types/code.py b/dspy/adapters/types/code.pyindex 9d8f81516..f9cf0eabb 100644--- a/dspy/adapters/types/code.py+++ b/dspy/adapters/types/code.py@@ -1,7 +1,8 @@import re-from typing import Any+from typing import Any, ClassVarimport pydantic+from pydantic import create_modelfrom dspy.adapters.types.base_type import Type@@ -23,7 +24,7 @@ class Code(Type):'''Generate python code to answer the question.'''question: str = dspy.InputField(description="The question to answer")- code: dspy.Code = dspy.OutputField(description="The code to execute")+ code: dspy.Code["java"] = dspy.OutputField(description="The code to execute")predict = dspy.Predict(CodeGeneration)@@ -43,7 +44,7 @@ class Code(Type):class CodeAnalysis(dspy.Signature):'''Analyze the time complexity of the function.'''- code: dspy.Code = dspy.InputField(description="The function to analyze")+ code: dspy.Code["python"] = dspy.InputField(description="The function to analyze")result: str = dspy.OutputField(description="The time complexity of the function")@@ -64,6 +65,8 @@ class Code(Type):code: str+ language: ClassVar[str] = "python"+def format(self):return f"{self.code}"@@ -76,7 +79,8 @@ class Code(Type):def description(cls) -> str:return ("Code represented in a string, specified in the `code` field. If this is an output field, the code "- "should follow the markdown code block format, e.g. \n```python\n{code}\n``` or \n```cpp\n{code}\n```."+ "field should follow the markdown code block format, e.g. \n```python\n{code}\n``` or \n```cpp\n{code}\n```"+ f"\nProgramming language: {cls.language}")@pydantic.model_validator(mode="before")@@ -115,3 +119,13 @@ def _filter_code(code: str) -> str:return match.group(1).strip()# Fallback casereturn code+++# Patch __class_getitem__ directly on the class to support dspy.Code["python"] syntax+def _code_class_getitem(cls, language):+ code_with_language_cls = create_model(f"{cls.__name__}_{language}", __base__=cls)+ code_with_language_cls.language = language+ return code_with_language_cls+++Code.__class_getitem__ = classmethod(_code_class_getitem)diff --git a/dspy/adapters/utils.py b/dspy/adapters/utils.pyindex b96ab24a2..2ce6de201 100644--- a/dspy/adapters/utils.py+++ b/dspy/adapters/utils.py@@ -171,7 +171,14 @@ def parse_value(value, annotation):try:return TypeAdapter(annotation).validate_python(candidate)- except pydantic.ValidationError:+ except pydantic.ValidationError as e:+ if issubclass(annotation, Type):+ try:+ # For dspy.Type, try parsing from the original value in case it has a custom parser+ return TypeAdapter(annotation).validate_python(value)+ except Exception:+ raise e+if origin is Union and type(None) in get_args(annotation) and str in get_args(annotation):return str(candidate)raisediff --git a/tests/adapters/test_code.py b/tests/adapters/test_code.pyindex 325c1eede..62d0c67ad 100644--- a/tests/adapters/test_code.py+++ b/tests/adapters/test_code.py@@ -8,18 +8,18 @@ import dspydef test_code_validate_input():# Create a `dspy.Code` instance with valid code.- code = dspy.Code(code="print('Hello, world!')")+ code = dspy.Code["python"](code="print('Hello, world!')")assert code.code == "print('Hello, world!')"with pytest.raises(ValueError):# Try to create a `dspy.Code` instance with invalid type.- dspy.Code(code=123)+ dspy.Code["python"](code=123)def foo(x):return x + 1code_source = inspect.getsource(foo)- code = dspy.Code(code=code_source)+ code = dspy.Code["python"](code=code_source)assert code.code == code_source@@ -33,6 +33,18 @@ def test_code_in_nested_type():assert wrapper.code.code == "print('Hello, world!')"+def test_code_with_language():+ java_code = dspy.Code["java"](code="System.out.println('Hello, world!');")+ assert java_code.code == "System.out.println('Hello, world!');"+ assert java_code.language == "java"+ assert "Programming language: java" in java_code.description()++ cpp_code = dspy.Code["cpp"](code="std::cout << 'Hello, world!' << std::endl;")+ assert cpp_code.code == "std::cout << 'Hello, world!' << std::endl;"+ assert cpp_code.language == "cpp"+ assert "Programming language: cpp" in cpp_code.description()++def test_code_parses_from_dirty_code():dirty_code = "```python\nprint('Hello, world!')```"code = dspy.Code(code=dirty_code)