DSPy: The framework for programming—not prompting—language models
Python
fix(JSONAdapter): Add escape logic if json mode but not structured outputs are supported (#8871)
Isaac Miller7f822bec15d0
diff --git a/dspy/adapters/json_adapter.py b/dspy/adapters/json_adapter.pyindex 898125f00..ae534d778 100644--- a/dspy/adapters/json_adapter.py+++ b/dspy/adapters/json_adapter.py@@ -52,7 +52,11 @@ class JSONAdapter(ChatAdapter):return call_fn(lm, lm_kwargs, signature, demos, inputs)has_tool_calls = any(field.annotation == ToolCalls for field in signature.output_fields.values())- if _has_open_ended_mapping(signature) or (not self.use_native_function_calling and has_tool_calls):+ # Some models support json mode but not structured outputs+ # Follows guidance from: https://docs.litellm.ai/docs/completion/json_mode#check-model-support+ supports_structured_outputs = litellm.supports_response_schema(model=lm.model, custom_llm_provider=provider)++ if _has_open_ended_mapping(signature) or (not self.use_native_function_calling and has_tool_calls) or not supports_structured_outputs:# We found that structured output mode doesn't work well with dspy.ToolCalls as output field.# So we fall back to json mode if native function calling is disabled and ToolCalls is present.lm_kwargs["response_format"] = {"type": "json_object"}diff --git a/tests/adapters/test_chat_adapter.py b/tests/adapters/test_chat_adapter.pyindex 0d5ee764c..0ea385630 100644--- a/tests/adapters/test_chat_adapter.py+++ b/tests/adapters/test_chat_adapter.py@@ -68,7 +68,7 @@ def test_chat_adapter_quotes_literals_as_expected(program = dspy.Predict(TestSignature)- dspy.configure(lm=dspy.LM(model="openai/gpt4o"), adapter=dspy.ChatAdapter())+ dspy.configure(lm=dspy.LM(model="openai/gpt-4o"), adapter=dspy.ChatAdapter())with mock.patch("litellm.completion") as mock_completion:program(input_text=input_value)@@ -121,7 +121,7 @@ def test_chat_adapter_with_pydantic_models():question: str = dspy.InputField()output: Answer = dspy.OutputField()- dspy.configure(lm=dspy.LM(model="openai/gpt4o"), adapter=dspy.ChatAdapter())+ dspy.configure(lm=dspy.LM(model="openai/gpt-4o"), adapter=dspy.ChatAdapter())program = dspy.Predict(TestSignature)with mock.patch("litellm.completion") as mock_completion:@@ -157,7 +157,7 @@ def test_chat_adapter_signature_information():input2: int = dspy.InputField(desc="Integer Input")output: str = dspy.OutputField(desc="String Output")- dspy.configure(lm=dspy.LM(model="openai/gpt4o"), adapter=dspy.ChatAdapter())+ dspy.configure(lm=dspy.LM(model="openai/gpt-4o"), adapter=dspy.ChatAdapter())program = dspy.Predict(TestSignature)with mock.patch("litellm.completion") as mock_completion:diff --git a/tests/adapters/test_json_adapter.py b/tests/adapters/test_json_adapter.pyindex c6ba8b238..51c1694ff 100644--- a/tests/adapters/test_json_adapter.py+++ b/tests/adapters/test_json_adapter.py@@ -72,7 +72,7 @@ def test_json_adapter_falls_back_when_structured_outputs_fails():input1: str = dspy.InputField()output1: str = dspy.OutputField(desc="String output field")- dspy.configure(lm=dspy.LM(model="openai/gpt4o", cache=False), adapter=dspy.JSONAdapter())+ dspy.configure(lm=dspy.LM(model="openai/gpt-4o", cache=False), adapter=dspy.JSONAdapter())program = dspy.Predict(TestSignature)with mock.patch("litellm.completion") as mock_completion:mock_completion.side_effect = [Exception("Bad structured outputs!"), mock_completion.return_value]@@ -96,7 +96,7 @@ def test_json_adapter_with_structured_outputs_does_not_mutate_original_signatureoutput3: OutputField3 = dspy.OutputField(desc="Nested output field")output4_unannotated = dspy.OutputField(desc="Unannotated output field")- dspy.configure(lm=dspy.LM(model="openai/gpt4o"), adapter=dspy.JSONAdapter())+ dspy.configure(lm=dspy.LM(model="openai/gpt-4o"), adapter=dspy.JSONAdapter())program = dspy.Predict(TestSignature)with mock.patch("litellm.completion"):program(input1="Test input")@@ -142,7 +142,7 @@ def test_json_adapter_on_pydantic_model():program = dspy.Predict(TestSignature)- dspy.configure(lm=dspy.LM(model="openai/gpt4o", cache=False), adapter=dspy.JSONAdapter())+ dspy.configure(lm=dspy.LM(model="openai/gpt-4o", cache=False), adapter=dspy.JSONAdapter())with mock.patch("litellm.completion") as mock_completion:mock_completion.return_value = ModelResponse(@@ -153,7 +153,7 @@ def test_json_adapter_on_pydantic_model():))],- model="openai/gpt4o",+ model="openai/gpt-4o",)result = program(user={"id": 5, "name": "name_test", "email": "email_test"}, question="What is the capital of France?"@@ -218,7 +218,7 @@ def test_json_adapter_parse_raise_error_on_mismatch_fields():choices=[Choices(message=Message(content="{'answer1': 'Paris'}")),],- model="openai/gpt4o",+ model="openai/gpt-4o",)lm = dspy.LM(model="openai/gpt-4o-mini")with pytest.raises(dspy.utils.exceptions.AdapterParseError) as e:@@ -554,10 +554,10 @@ async def test_json_adapter_on_pydantic_model_async():))],- model="openai/gpt4o",+ model="openai/gpt-4o",)- with dspy.context(lm=dspy.LM(model="openai/gpt4o", cache=False), adapter=dspy.JSONAdapter()):+ with dspy.context(lm=dspy.LM(model="openai/gpt-4o", cache=False), adapter=dspy.JSONAdapter()):result = await program.acall(user={"id": 5, "name": "name_test", "email": "email_test"}, question="What is the capital of France?")@@ -641,6 +641,56 @@ def test_json_adapter_fallback_to_json_mode_on_structured_output_failure():_, second_call_kwargs = mock_completion.call_args_list[1]assert second_call_kwargs.get("response_format") == {"type": "json_object"}+def test_json_adapter_json_mode_no_structured_outputs():+ class TestSignature(dspy.Signature):+ question: str = dspy.InputField()+ answer: str = dspy.OutputField(desc="String output field")++ dspy.configure(lm=dspy.LM(model="openai/gpt-4o", cache=False), adapter=dspy.JSONAdapter())+ program = dspy.Predict(TestSignature)++ with mock.patch("litellm.completion") as mock_completion, \+ mock.patch("litellm.get_supported_openai_params") as mock_get_supported_openai_params, \+ mock.patch("litellm.supports_response_schema") as mock_supports_response_schema:+ # Call a model that allows json but not structured outputs+ mock_completion.return_value = ModelResponse(choices=[Choices(message=Message(content="{'answer': 'Test output'}"))])+ mock_get_supported_openai_params.return_value = ["response_format"]+ mock_supports_response_schema.return_value = False++ result = program(question="Dummy question!")++ assert mock_completion.call_count == 1+ assert result.answer == "Test output"++ _, call_kwargs = mock_completion.call_args_list[0]+ assert call_kwargs.get("response_format") == {"type": "json_object"}+++async def test_json_adapter_json_mode_no_structured_outputs_async():+ class TestSignature(dspy.Signature):+ question: str = dspy.InputField()+ answer: str = dspy.OutputField(desc="String output field")++ program = dspy.Predict(TestSignature)++ with mock.patch("litellm.acompletion") as mock_acompletion, \+ mock.patch("litellm.get_supported_openai_params") as mock_get_supported_openai_params, \+ mock.patch("litellm.supports_response_schema") as mock_supports_response_schema:+ # Call a model that allows json but not structured outputs+ mock_acompletion.return_value = ModelResponse(choices=[Choices(message=Message(content="{'answer': 'Test output'}"))])+ mock_get_supported_openai_params.return_value = ["response_format"]+ mock_supports_response_schema.return_value = False++ with dspy.context(lm=dspy.LM(model="openai/gpt-4o", cache=False), adapter=dspy.JSONAdapter()):+ result = await program.acall(question="Dummy question!")++ assert mock_acompletion.call_count == 1+ assert result.answer == "Test output"++ _, call_kwargs = mock_acompletion.call_args_list[0]+ assert call_kwargs.get("response_format") == {"type": "json_object"}+@pytest.mark.asyncioasync def test_json_adapter_fallback_to_json_mode_on_structured_output_failure_async():