Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

feat(adapter): Fix behavior for optional/default output fields (#10148)

Michael I.ba8a64958d9b
diff --git a/docs/docs/learn/programming/signatures.md b/docs/docs/learn/programming/signatures.md
index 9b3da5f97..737a6d964 100644
--- a/docs/docs/learn/programming/signatures.md
+++ b/docs/docs/learn/programming/signatures.md
@@ -235,6 +235,22 @@ predictor = dspy.Predict("number: int -> result: str")
predictor(number="42") # No warning
```
+### Optional Output Fields
+
+Output fields are required by default: if the LM response does not contain a declared output field, the adapter raises an `AdapterParseError`. An output field becomes optional when it declares a default value, a `default_factory`, or an annotation that allows `None`. When the LM omits an optional field, the parsed prediction falls back to the default, the factory result, or `None`, in that order of precedence.
+
+```python
+class Extract(dspy.Signature):
+ """Extract structured information from text."""
+ text: str = dspy.InputField()
+ title: str = dspy.OutputField() # required: missing -> AdapterParseError
+ note: str | None = dspy.OutputField(default="No note") # missing -> "No note"
+ tags: list[str] = dspy.OutputField(default_factory=list) # missing -> []
+ subtitle: str | None = dspy.OutputField() # missing -> None
+```
+
+As for input fields: a missing input with a default is filled into the prompt, an input whose annotation allows `None` is omitted from the prompt, and a missing required input logs a warning.
+
## Using signatures to build modules & compiling them
While signatures are convenient for prototyping with structured inputs/outputs, that's not the only reason to use them!
diff --git a/dspy/adapters/base.py b/dspy/adapters/base.py
index 3e2ffa599..0e1329de3 100644
--- a/dspy/adapters/base.py
+++ b/dspy/adapters/base.py
@@ -11,7 +11,7 @@ from dspy.adapters._legacy_type_markers import (
from dspy.adapters.types import History, Type
from dspy.adapters.types.reasoning import Reasoning
from dspy.adapters.types.tool import Tool, ToolCallResults, ToolCalls
-from dspy.adapters.utils import serialize_for_json
+from dspy.adapters.utils import apply_output_field_defaults, serialize_for_json
from dspy.clients.base_lm import BaseLM
from dspy.clients.openai_format import (
legacy_outputs_from_lm_response,
@@ -176,7 +176,8 @@ class Adapter:
message="The LM returned an empty or null response.",
)
- # Fields removed for native features are absent from the processed parse.
+ # Fields removed for native features are absent from the processed parse
+ value = apply_output_field_defaults(original_signature, value)
for field_name in original_signature.output_fields:
value.setdefault(field_name, None)
diff --git a/dspy/adapters/chat_adapter.py b/dspy/adapters/chat_adapter.py
index 6992ff9ce..06d2f90ed 100644
--- a/dspy/adapters/chat_adapter.py
+++ b/dspy/adapters/chat_adapter.py
@@ -7,6 +7,7 @@ from pydantic.fields import FieldInfo
from dspy.adapters.base import Adapter
from dspy.adapters.types.tool import ToolCalls
from dspy.adapters.utils import (
+ apply_output_field_defaults,
format_field_value,
get_annotation_name,
get_field_description_string,
@@ -242,6 +243,7 @@ class ChatAdapter(Adapter):
lm_response=completion,
message=f"Failed to parse field {k} with value {v} from the LM response. Error message: {e}",
)
+ fields = apply_output_field_defaults(signature, fields)
if fields.keys() != signature.output_fields.keys():
raise AdapterParseError(
adapter_name="ChatAdapter",
diff --git a/dspy/adapters/json_adapter.py b/dspy/adapters/json_adapter.py
index fcc8d3e52..286f3e4ac 100644
--- a/dspy/adapters/json_adapter.py
+++ b/dspy/adapters/json_adapter.py
@@ -10,6 +10,7 @@ from pydantic.fields import FieldInfo
from dspy.adapters.chat_adapter import ChatAdapter, FieldInfoWithName
from dspy.adapters.types.tool import ToolCalls
from dspy.adapters.utils import (
+ apply_output_field_defaults,
format_field_value,
get_annotation_name,
parse_value,
@@ -189,6 +190,7 @@ class JSONAdapter(ChatAdapter):
if k in signature.output_fields:
fields[k] = parse_value(v, signature.output_fields[k].annotation)
+ fields = apply_output_field_defaults(signature, fields)
if fields.keys() != signature.output_fields.keys():
raise AdapterParseError(
adapter_name="JSONAdapter",
diff --git a/dspy/adapters/utils.py b/dspy/adapters/utils.py
index b45eda559..bdd308a00 100644
--- a/dspy/adapters/utils.py
+++ b/dspy/adapters/utils.py
@@ -4,7 +4,7 @@ import inspect
import json
import types
from collections.abc import Mapping
-from typing import Any, Literal, Union, get_args, get_origin
+from typing import TYPE_CHECKING, Annotated, Any, Literal, Union, get_args, get_origin
import json_repair
import pydantic
@@ -16,6 +16,44 @@ from dspy.adapters.types.code import Code
from dspy.adapters.types.reasoning import Reasoning
from dspy.signatures.utils import get_dspy_field_type
+if TYPE_CHECKING:
+ from dspy.signatures.signature import Signature
+
+
+def annotation_allows_none(annotation: Any) -> bool:
+ """Whether the annotation admits None (e.g. `str | None`, `Optional[str]`, `None`)."""
+ if annotation is None or annotation is type(None):
+ return True
+
+ origin = get_origin(annotation)
+ args = get_args(annotation)
+
+ if origin is Annotated:
+ return bool(args) and annotation_allows_none(args[0])
+
+ if origin is Union or origin is types.UnionType:
+ return any(annotation_allows_none(arg) for arg in args)
+
+ return False
+
+
+def apply_output_field_defaults(signature: "type[Signature]", fields: dict[str, Any]) -> dict[str, Any]:
+ """
+ Fill output fields that are missing from a parsed LM response, in signature order.
+
+ An output field is optional when it declares a default, a default factory, or an annotation
+ that allows None; a missing optional field takes that fallback (in that order of precedence).
+ """
+ completed = {}
+ for name, field_info in signature.output_fields.items():
+ if name in fields:
+ completed[name] = fields[name]
+ elif not field_info.is_required():
+ completed[name] = field_info.get_default(call_default_factory=True)
+ elif annotation_allows_none(field_info.annotation):
+ completed[name] = None
+ return completed
+
def _annotation_is_subclass(annotation: Any, expected_base: type) -> bool:
try:
diff --git a/dspy/adapters/xml_adapter.py b/dspy/adapters/xml_adapter.py
index 306c2afcc..654fc2f70 100644
--- a/dspy/adapters/xml_adapter.py
+++ b/dspy/adapters/xml_adapter.py
@@ -4,7 +4,7 @@ from typing import Any
from pydantic.fields import FieldInfo
from dspy.adapters.chat_adapter import ChatAdapter, FieldInfoWithName
-from dspy.adapters.utils import format_field_value, translate_field_type
+from dspy.adapters.utils import apply_output_field_defaults, format_field_value, translate_field_type
from dspy.signatures.signature import Signature
@@ -92,6 +92,7 @@ class XMLAdapter(ChatAdapter):
# Cast values using base class parse_value helper
for k, v in fields.items():
fields[k] = self._parse_field_value(signature.output_fields[k], v, completion, signature)
+ fields = apply_output_field_defaults(signature, fields)
if fields.keys() != signature.output_fields.keys():
from dspy.utils.exceptions import AdapterParseError
diff --git a/dspy/predict/flex/bridge.py b/dspy/predict/flex/bridge.py
index bc8bb59a0..cc3a63b1f 100644
--- a/dspy/predict/flex/bridge.py
+++ b/dspy/predict/flex/bridge.py
@@ -32,9 +32,8 @@ import functools
import inspect
import json
import logging
-import types
from pathlib import Path
-from typing import Any, Callable, Union, get_args, get_origin
+from typing import Any, Callable
from pydantic import TypeAdapter
from pydantic_core import PydanticSerializationError, to_jsonable_python
@@ -42,7 +41,7 @@ from pydantic_core import PydanticSerializationError, to_jsonable_python
import dspy
from dspy import CodeInterpreterError
from dspy.adapters.types.base_type import Type as _CustomType
-from dspy.adapters.utils import parse_value
+from dspy.adapters.utils import annotation_allows_none, parse_value
from dspy.primitives.code_interpreter import _create_interpreter
from dspy.signatures.signature import make_signature
from dspy.utils.exceptions import LMError
@@ -178,13 +177,6 @@ def _restore_custom_types(value: Any, originals: dict[str, Any]) -> Any:
return value
-def _is_field_optional(annotation: Any) -> bool:
- """True if the field annotation is optional, a union admitting None."""
- return annotation is type(None) or (
- get_origin(annotation) in (Union, types.UnionType) and type(None) in get_args(annotation)
- )
-
-
class _Invocation:
"""Per-forward bridge state: the predictors this forward constructed (keyed by the sandbox
attribute name), its predictor-call budget, and the original custom-type objects to restore
@@ -307,7 +299,7 @@ class BridgeRuntime:
if not field.is_required():
out[name] = field.get_default(call_default_factory=True)
filled.add(name)
- elif _is_field_optional(field.annotation):
+ elif annotation_allows_none(field.annotation):
out[name] = None
filled.add(name)
else:
diff --git a/dspy/predict/predict.py b/dspy/predict/predict.py
index 2018cffaa..8f3662353 100644
--- a/dspy/predict/predict.py
+++ b/dspy/predict/predict.py
@@ -1,12 +1,13 @@
import logging
import random
import types
-from typing import Annotated, Any, Literal, Union, get_args, get_origin
+from typing import Any, Literal, Union, get_args, get_origin
from pydantic import BaseModel
from pydantic_core import PydanticUndefined
from dspy.adapters.chat_adapter import ChatAdapter
+from dspy.adapters.utils import annotation_allows_none
from dspy.clients.base_lm import BaseLM
from dspy.dsp.utils.settings import settings
from dspy.predict.parameter import Parameter
@@ -219,7 +220,7 @@ class Predict(Module, Parameter):
missing = [
k
for k, field_info in signature.input_fields.items()
- if k not in kwargs and not _annotation_allows_none(field_info.annotation)
+ if k not in kwargs and not annotation_allows_none(field_info.annotation)
]
if missing:
present = [k for k in signature.input_fields if k in kwargs]
@@ -310,22 +311,6 @@ def _get_type_name(type_annotation) -> str:
return getattr(origin, "__name__", str(origin))
-def _annotation_allows_none(annotation: Any) -> bool:
- origin = get_origin(annotation)
- args = get_args(annotation)
-
- if annotation is None or annotation is type(None):
- return True
-
- if origin is Annotated:
- return bool(args) and _annotation_allows_none(args[0])
-
- if origin is Union or origin is types.UnionType:
- return any(_annotation_allows_none(arg) for arg in args)
-
- return False
-
-
def _is_value_compatible_with_type(value: Any, expected: type) -> bool:
"""Return True if the value matches the expected type hint."""
# Special handle list[str] because we allow setting input type to str, however, invoking with a list thereof.
diff --git a/tests/adapters/test_chat_adapter.py b/tests/adapters/test_chat_adapter.py
index c4db04d11..67ebdfa42 100644
--- a/tests/adapters/test_chat_adapter.py
+++ b/tests/adapters/test_chat_adapter.py
@@ -2866,3 +2866,83 @@ def test_provider_tool_calls_preserve_id_and_repair_arguments():
dspy.ToolCalls.ToolCall(id="call_from_responses", name="search", args={"query": "cats"})
]
)
+
+
+class OptionalOutputSignature(dspy.Signature):
+ question: str = dspy.InputField()
+ answer: str = dspy.OutputField()
+ note: str | None = dspy.OutputField(default="No note")
+ tags: list[str] = dspy.OutputField(default_factory=list)
+ maybe: str | None = dspy.OutputField()
+
+
+def test_missing_optional_output_fields_fall_back_to_defaults():
+ from dspy.utils.dummies import DummyLM
+
+ with dspy.context(lm=DummyLM([{"answer": "42"}]), adapter=dspy.ChatAdapter()):
+ pred = dspy.Predict(OptionalOutputSignature)(question="anything")
+
+ assert pred.answer == "42"
+ assert pred.note == "No note"
+ assert pred.tags == []
+ assert pred.maybe is None
+
+
+def test_output_field_default_is_overridden_by_lm_response():
+ from dspy.utils.dummies import DummyLM
+
+ with dspy.context(lm=DummyLM([{"answer": "42", "note": "hello", "tags": '["a"]', "maybe": "yes"}]),
+ adapter=dspy.ChatAdapter()):
+ pred = dspy.Predict(OptionalOutputSignature)(question="anything")
+
+ assert pred.note == "hello"
+ assert pred.tags == ["a"]
+ assert pred.maybe == "yes"
+
+
+def test_missing_required_output_field_still_raises():
+ from dspy.utils.dummies import DummyLM
+ from dspy.utils.exceptions import AdapterParseError
+
+ # Two identical responses: ChatAdapter retries via the JSONAdapter fallback before raising.
+ responses = [{"note": "present"}, {"note": "present"}]
+ with dspy.context(lm=DummyLM(responses), adapter=dspy.ChatAdapter()):
+ with pytest.raises(AdapterParseError):
+ dspy.Predict(OptionalOutputSignature)(question="anything")
+
+
+def test_optional_type_syntax_output_fields_fall_back_to_defaults():
+ from typing import Optional
+
+ from dspy.utils.dummies import DummyLM
+
+ class OptionalSyntaxSignature(dspy.Signature):
+ question: str = dspy.InputField()
+ answer: str = dspy.OutputField()
+ note: Optional[str] = dspy.OutputField(default="No note") # noqa: UP045
+ maybe: Optional[str] = dspy.OutputField() # noqa: UP045
+
+ with dspy.context(lm=DummyLM([{"answer": "42"}]), adapter=dspy.ChatAdapter()):
+ pred = dspy.Predict(OptionalSyntaxSignature)(question="anything")
+
+ assert pred.answer == "42"
+ assert pred.note == "No note"
+ assert pred.maybe is None
+
+
+def test_optional_type_syntax_missing_required_output_field_still_raises():
+ from typing import Optional
+
+ from dspy.utils.dummies import DummyLM
+ from dspy.utils.exceptions import AdapterParseError
+
+ class OptionalSyntaxSignature(dspy.Signature):
+ question: str = dspy.InputField()
+ answer: str = dspy.OutputField()
+ note: Optional[str] = dspy.OutputField(default="No note") # noqa: UP045
+ maybe: Optional[str] = dspy.OutputField() # noqa: UP045
+
+ responses = [{"note": "present"}, {"maybe": "present"}]
+ with dspy.context(lm=DummyLM(responses), adapter=dspy.ChatAdapter()):
+ with pytest.raises(AdapterParseError):
+ dspy.Predict(OptionalSyntaxSignature)(question="anything")
diff --git a/tests/adapters/test_json_adapter.py b/tests/adapters/test_json_adapter.py
index 4d5efee0b..63e07e171 100644
--- a/tests/adapters/test_json_adapter.py
+++ b/tests/adapters/test_json_adapter.py
@@ -1699,3 +1699,20 @@ Outputs will be a JSON object with the following fields.
In adhering to this structure, your objective is:\x20
Answer the question with multiple answers and scores"""
assert system_message == expected_system_message
+
+
+def test_missing_optional_output_fields_fall_back_to_defaults():
+ from dspy.utils.exceptions import AdapterParseError
+
+ class OptionalOutputSignature(dspy.Signature):
+ question: str = dspy.InputField()
+ answer: str = dspy.OutputField()
+ note: str | None = dspy.OutputField(default="No note")
+ maybe: str | None = dspy.OutputField()
+
+ adapter = dspy.JSONAdapter()
+ parsed = adapter.parse(OptionalOutputSignature, '{"answer": "42"}')
+ assert parsed == {"answer": "42", "note": "No note", "maybe": None}
+
+ with pytest.raises(AdapterParseError):
+ adapter.parse(OptionalOutputSignature, '{"note": "present"}')
diff --git a/tests/adapters/test_reasoning.py b/tests/adapters/test_reasoning.py
index 90812b81c..848d324e9 100644
--- a/tests/adapters/test_reasoning.py
+++ b/tests/adapters/test_reasoning.py
@@ -109,3 +109,21 @@ def test_reasoning_error_message():
with pytest.raises(AttributeError, match="`Reasoning` object has no attribute 'nonexistent_method'"):
reasoning.nonexistent_method
+
+
+def test_native_reasoning_default_survives_provider_omission():
+ class Sig(dspy.Signature):
+ question: str = dspy.InputField()
+ answer: str = dspy.OutputField()
+ reasoning: dspy.Reasoning = dspy.OutputField(default_factory=lambda: dspy.Reasoning(content="(omitted)"))
+
+ adapter = dspy.ChatAdapter()
+ # Native reasoning strips the field from the signature the LM formats against; the provider
+ # then omits native reasoning entirely.
+ processed = Sig.delete("reasoning")
+ outputs = [{"text": "[[ ## answer ## ]]\n42\n\n[[ ## completed ## ]]"}]
+
+ value = adapter._call_postprocess(processed, Sig, outputs, None, {})[0]
+
+ assert value["answer"] == "42"
+ assert value["reasoning"] == dspy.Reasoning(content="(omitted)")
diff --git a/tests/adapters/test_xml_adapter.py b/tests/adapters/test_xml_adapter.py
index b0f04f118..139bf6394 100644
--- a/tests/adapters/test_xml_adapter.py
+++ b/tests/adapters/test_xml_adapter.py
@@ -841,3 +841,15 @@ All interactions will be structured in the following way, with the appropriate v
In adhering to this structure, your objective is:\x20
Answer the question with multiple answers and scores"""
assert system_message == expected_system_message
+
+
+def test_xml_adapter_missing_optional_output_fields_fall_back_to_defaults():
+ class TestSignature(dspy.Signature):
+ question: str = dspy.InputField()
+ answer: str = dspy.OutputField()
+ note: str | None = dspy.OutputField(default="No note")
+ maybe: str | None = dspy.OutputField()
+
+ adapter = XMLAdapter()
+ parsed = adapter.parse(TestSignature, "<answer>Paris</answer>")
+ assert parsed == {"answer": "Paris", "note": "No note", "maybe": None}