DSPy: The framework for programming—not prompting—language models
Python
fix(adapters): skip JSON schema for DSPy custom types in prompt (#9251) (#9257)
Darin35c19acbe164
diff --git a/dspy/adapters/utils.py b/dspy/adapters/utils.pyindex fc87d2d6e..4e9866ed2 100644--- a/dspy/adapters/utils.py+++ b/dspy/adapters/utils.py@@ -12,6 +12,7 @@ from pydantic import TypeAdapterfrom pydantic.fields import FieldInfofrom dspy.adapters.types.base_type import Type as DspyType+from dspy.adapters.types.code import Codefrom dspy.adapters.types.reasoning import Reasoningfrom dspy.signatures.utils import get_dspy_field_type@@ -100,6 +101,9 @@ def translate_field_type(field_name, field_info):# literal or returning a value of the form 'Literal[<selected_value>]'f"must exactly match (no extra characters) one of: {'; '.join([str(x) for x in field_type.__args__])}")+ elif inspect.isclass(field_type) and issubclass(field_type, Code) and field_type.description():+ # Code has a rich type description already; avoid duplicating its large schema block.+ desc = ""else:desc = f"must adhere to the JSON schema: {json.dumps(_get_json_schema(field_type), ensure_ascii=False)}"diff --git a/tests/adapters/test_chat_adapter.py b/tests/adapters/test_chat_adapter.pyindex adb0dfed2..dd6a76c19 100644--- a/tests/adapters/test_chat_adapter.py+++ b/tests/adapters/test_chat_adapter.py@@ -6,6 +6,7 @@ import pytestfrom litellm.utils import ChatCompletionMessageToolCall, Choices, Function, Message, ModelResponseimport dspy+from dspy.experimental import Citations@pytest.mark.parametrize(@@ -398,6 +399,38 @@ def test_chat_adapter_with_code():assert result[0]["code"].code == 'print("Hello, world!")'+def test_code_output_field_omits_json_schema_in_prompt():+ """Regression test for #9251: dspy.Code should avoid duplicating large JSON schema text."""+ class CodeGeneration(dspy.Signature):+ """Generate code to answer the question"""+ question: str = dspy.InputField()+ code: dspy.Code = dspy.OutputField()++ adapter = dspy.ChatAdapter()+ messages = adapter.format(CodeGeneration, [], {"question": "Hello"})+ system_content = messages[0]["content"]++ assert dspy.Code.description() in system_content+ assert "JSON schema" not in system_content+ assert '"properties"' not in system_content+ assert "Code type in DSPy" not in system_content+++def test_citations_output_field_keeps_json_schema_in_prompt():+ """Non-Code custom types should keep schema guidance for structured output reliability."""++ class CitationGeneration(dspy.Signature):+ question: str = dspy.InputField()+ citations: Citations = dspy.OutputField()++ adapter = dspy.ChatAdapter()+ messages = adapter.format(CitationGeneration, [], {"question": "Hello"})+ system_content = messages[0]["content"]++ assert "must adhere to the JSON schema" in system_content+ assert "Type description of Citations" in system_content++def test_chat_adapter_formats_conversation_history():class MySignature(dspy.Signature):question: str = dspy.InputField()