DSPy: The framework for programming—not prompting—language models
Python
add dspy.Code (#8511)
Chen Qian9006fbd09b3f
diff --git a/dspy/__init__.py b/dspy/__init__.pyindex 25ba18f3a..ea4c75a86 100644--- a/dspy/__init__.py+++ b/dspy/__init__.py@@ -6,7 +6,7 @@ from dspy.teleprompt import *from dspy.evaluate import Evaluate # isort: skipfrom dspy.clients import * # isort: skip-from dspy.adapters import Adapter, ChatAdapter, JSONAdapter, XMLAdapter, TwoStepAdapter, Image, Audio, History, Type, Tool, ToolCalls # isort: skip+from dspy.adapters import Adapter, ChatAdapter, JSONAdapter, XMLAdapter, TwoStepAdapter, Image, Audio, History, Type, Tool, ToolCalls, Code # isort: skipfrom dspy.utils.logging_utils import configure_dspy_loggers, disable_logging, enable_loggingfrom dspy.utils.asyncify import asyncifyfrom dspy.utils.syncify import syncifydiff --git a/dspy/adapters/__init__.py b/dspy/adapters/__init__.pyindex c2c6d23a3..1dea6da47 100644--- a/dspy/adapters/__init__.py+++ b/dspy/adapters/__init__.py@@ -2,7 +2,7 @@ from dspy.adapters.base import Adapterfrom dspy.adapters.chat_adapter import ChatAdapterfrom dspy.adapters.json_adapter import JSONAdapterfrom dspy.adapters.two_step_adapter import TwoStepAdapter-from dspy.adapters.types import Audio, History, Image, Tool, ToolCalls, Type+from dspy.adapters.types import Audio, Code, History, Image, Tool, ToolCalls, Typefrom dspy.adapters.xml_adapter import XMLAdapter__all__ = [@@ -12,6 +12,7 @@ __all__ = ["History","Image","Audio",+ "Code","JSONAdapter","XMLAdapter","TwoStepAdapter",diff --git a/dspy/adapters/types/__init__.py b/dspy/adapters/types/__init__.pyindex bc57d50d5..11b9faee1 100644--- a/dspy/adapters/types/__init__.py+++ b/dspy/adapters/types/__init__.py@@ -1,7 +1,8 @@from dspy.adapters.types.audio import Audiofrom dspy.adapters.types.base_type import Type+from dspy.adapters.types.code import Codefrom dspy.adapters.types.history import Historyfrom dspy.adapters.types.image import Imagefrom dspy.adapters.types.tool import Tool, ToolCalls-__all__ = ["History", "Image", "Audio", "Type", "Tool", "ToolCalls"]+__all__ = ["History", "Image", "Audio", "Type", "Tool", "ToolCalls", "Code"]diff --git a/dspy/adapters/types/code.py b/dspy/adapters/types/code.pynew file mode 100644index 000000000..9d8f81516--- /dev/null+++ b/dspy/adapters/types/code.py@@ -0,0 +1,117 @@+import re+from typing import Any++import pydantic++from dspy.adapters.types.base_type import Type+++class Code(Type):+ """Code type in DSPy.++ This type is useful for code generation and code analysis.++ Example 1: dspy.Code as output type in code generation:++ ```python+ import dspy++ dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))+++ class CodeGeneration(dspy.Signature):+ '''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")+++ predict = dspy.Predict(CodeGeneration)++ result = predict(question="Given an array, find if any of the two numbers sum up to 10")+ print(result.code)+ ```++ Example 2: dspy.Code as input type in code analysis:++ ```python+ import dspy+ import inspect++ dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))++ class CodeAnalysis(dspy.Signature):+ '''Analyze the time complexity of the function.'''++ code: dspy.Code = dspy.InputField(description="The function to analyze")+ result: str = dspy.OutputField(description="The time complexity of the function")+++ predict = dspy.Predict(CodeAnalysis)+++ def sleepsort(x):+ import time++ for i in x:+ time.sleep(i)+ print(i)++ result = predict(code=inspect.getsource(sleepsort))+ print(result.result)+ ```+ """++ code: str++ def format(self):+ return f"{self.code}"++ @pydantic.model_serializer()+ def serialize_model(self):+ """Override to bypass the <<CUSTOM-TYPE-START-IDENTIFIER>> and <<CUSTOM-TYPE-END-IDENTIFIER>> tags."""+ return self.format()++ @classmethod+ 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```."+ )++ @pydantic.model_validator(mode="before")+ @classmethod+ def validate_input(cls, data: Any):+ if isinstance(data, cls):+ return data++ if isinstance(data, str):+ return {"code": _filter_code(data)}++ if isinstance(data, dict):+ if "code" not in data:+ raise ValueError("`code` field is required for `dspy.Code`")+ if not isinstance(data["code"], str):+ raise ValueError(f"`code` field must be a string, but received type: {type(data['code'])}")+ return {"code": _filter_code(data["code"])}++ raise ValueError(f"Received invalid value for `dspy.Code`: {data}")+++def _filter_code(code: str) -> str:+ """Extract code from markdown code blocks, stripping any language identifier."""+ # Case 1: format like:+ # ```python+ # {code_block}+ # ```+ regex_pattern = r"```(?:[^\n]*)\n(.*?)```"+ match = re.search(regex_pattern, code, re.DOTALL)+ if match:+ return match.group(1).strip()+ # Case 2: ```<code>``` (no language, single-line)+ regex_pattern_simple = r"```(.*?)```"+ match = re.search(regex_pattern_simple, code, re.DOTALL)+ if match:+ return match.group(1).strip()+ # Fallback case+ return codediff --git a/tests/adapters/test_chat_adapter.py b/tests/adapters/test_chat_adapter.pyindex 457ba0b0e..98e892e8d 100644--- a/tests/adapters/test_chat_adapter.py+++ b/tests/adapters/test_chat_adapter.py@@ -356,6 +356,48 @@ def test_chat_adapter_with_tool():assert "{'country': {'type': 'string'}, 'year': {'type': 'integer'}}" in messages[1]["content"]+def test_chat_adapter_with_code():+ # Test with code as input field+ class CodeAnalysis(dspy.Signature):+ """Analyze the time complexity of the code"""++ code: dspy.Code = dspy.InputField()+ result: str = dspy.OutputField()++ adapter = dspy.ChatAdapter()+ messages = adapter.format(CodeAnalysis, [], {"code": "print('Hello, world!')"})++ assert len(messages) == 2++ # The output field type description should be included in the system message even if the output field is nested+ assert dspy.Code.description() in messages[0]["content"]++ # The user message should include the question and the tools+ assert "print('Hello, world!')" in messages[1]["content"]++ # Test with code as output field+ class CodeGeneration(dspy.Signature):+ """Generate code to answer the question"""++ question: str = dspy.InputField()+ code: dspy.Code = dspy.OutputField()++ adapter = dspy.ChatAdapter()+ with mock.patch("litellm.completion") as mock_completion:+ mock_completion.return_value = ModelResponse(+ choices=[Choices(message=Message(content='[[ ## code ## ]]\nprint("Hello, world!")'))],+ model="openai/gpt-4o-mini",+ )+ result = adapter(+ dspy.LM(model="openai/gpt-4o-mini", cache=False),+ {},+ CodeGeneration,+ [],+ {"question": "Write a python program to print 'Hello, world!'"},+ )+ assert result[0]["code"].code == 'print("Hello, world!")'++def test_chat_adapter_formats_conversation_history():class MySignature(dspy.Signature):question: str = dspy.InputField()diff --git a/tests/adapters/test_code.py b/tests/adapters/test_code.pynew file mode 100644index 000000000..325c1eede--- /dev/null+++ b/tests/adapters/test_code.py@@ -0,0 +1,51 @@+import inspect++import pydantic+import pytest++import dspy+++def test_code_validate_input():+ # Create a `dspy.Code` instance with valid code.+ code = dspy.Code(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)++ def foo(x):+ return x + 1++ code_source = inspect.getsource(foo)+ code = dspy.Code(code=code_source)++ assert code.code == code_source+++def test_code_in_nested_type():+ class Wrapper(pydantic.BaseModel):+ code: dspy.Code++ code = dspy.Code(code="print('Hello, world!')")+ wrapper = Wrapper(code=code)+ assert wrapper.code.code == "print('Hello, world!')"+++def test_code_parses_from_dirty_code():+ dirty_code = "```python\nprint('Hello, world!')```"+ code = dspy.Code(code=dirty_code)+ assert code.code == "print('Hello, world!')"++ dirty_code_with_reasoning = """+The generated code is:+```python+print('Hello, world!')+```++The reasoning is:+The code is a simple print statement.+"""+ code = dspy.Code(code=dirty_code_with_reasoning)+ assert code.code == "print('Hello, world!')"diff --git a/tests/adapters/test_json_adapter.py b/tests/adapters/test_json_adapter.pyindex d58e5f9ef..893dcd30d 100644--- a/tests/adapters/test_json_adapter.py+++ b/tests/adapters/test_json_adapter.py@@ -435,6 +435,48 @@ def test_json_adapter_with_tool():}+def test_json_adapter_with_code():+ # Test with code as input field+ class CodeAnalysis(dspy.Signature):+ """Analyze the time complexity of the code"""++ code: dspy.Code = dspy.InputField()+ result: str = dspy.OutputField()++ adapter = dspy.JSONAdapter()+ messages = adapter.format(CodeAnalysis, [], {"code": "print('Hello, world!')"})++ assert len(messages) == 2++ # The output field type description should be included in the system message even if the output field is nested+ assert dspy.Code.description() in messages[0]["content"]++ # The user message should include the question and the tools+ assert "print('Hello, world!')" in messages[1]["content"]++ # Test with code as output field+ class CodeGeneration(dspy.Signature):+ """Generate code to answer the question"""++ question: str = dspy.InputField()+ code: dspy.Code = dspy.OutputField()++ adapter = dspy.JSONAdapter()+ with mock.patch("litellm.completion") as mock_completion:+ mock_completion.return_value = ModelResponse(+ choices=[Choices(message=Message(content="{'code': 'print(\"Hello, world!\")'}"))],+ model="openai/gpt-4o-mini",+ )+ result = adapter(+ dspy.LM(model="openai/gpt-4o-mini", cache=False),+ {},+ CodeGeneration,+ [],+ {"question": "Write a python program to print 'Hello, world!'"},+ )+ assert result[0]["code"].code == 'print("Hello, world!")'++def test_json_adapter_formats_conversation_history():class MySignature(dspy.Signature):question: str = dspy.InputField()diff --git a/tests/adapters/test_xml_adapter.py b/tests/adapters/test_xml_adapter.pyindex f47884d3f..51c744bb4 100644--- a/tests/adapters/test_xml_adapter.py+++ b/tests/adapters/test_xml_adapter.py@@ -1,5 +1,8 @@+from unittest import mock+import pydanticimport pytest+from litellm import Choices, Message, ModelResponseimport dspyfrom dspy.adapters.chat_adapter import FieldInfoWithName@@ -216,3 +219,45 @@ def test_xml_adapter_formats_nested_images():# The query image is formatted in the last user messageassert {"type": "image_url", "image_url": {"url": "https://example.com/image4.jpg"}} in messages[-1]["content"]+++def test_xml_adapter_with_code():+ # Test with code as input field+ class CodeAnalysis(dspy.Signature):+ """Analyze the time complexity of the code"""++ code: dspy.Code = dspy.InputField()+ result: str = dspy.OutputField()++ adapter = dspy.XMLAdapter()+ messages = adapter.format(CodeAnalysis, [], {"code": "print('Hello, world!')"})++ assert len(messages) == 2++ # The output field type description should be included in the system message even if the output field is nested+ assert dspy.Code.description() in messages[0]["content"]++ # The user message should include the question and the tools+ assert "print('Hello, world!')" in messages[1]["content"]++ # Test with code as output field+ class CodeGeneration(dspy.Signature):+ """Generate code to answer the question"""++ question: str = dspy.InputField()+ code: dspy.Code = dspy.OutputField()++ adapter = dspy.XMLAdapter()+ with mock.patch("litellm.completion") as mock_completion:+ mock_completion.return_value = ModelResponse(+ choices=[Choices(message=Message(content='<code>print("Hello, world!")</code>'))],+ model="openai/gpt-4o-mini",+ )+ result = adapter(+ dspy.LM(model="openai/gpt-4o-mini", cache=False),+ {},+ CodeGeneration,+ [],+ {"question": "Write a python program to print 'Hello, world!'"},+ )+ assert result[0]["code"].code == 'print("Hello, world!")'