Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Patch `dspy.gepa` to handle `list[dict]` output from a `dspy.LM` (#9169)

Marius Arvinte0d595395e863
diff --git a/dspy/teleprompt/gepa/gepa.py b/dspy/teleprompt/gepa/gepa.py
index c44850694..d0427ffeb 100644
--- a/dspy/teleprompt/gepa/gepa.py
+++ b/dspy/teleprompt/gepa/gepa.py
@@ -653,7 +653,7 @@ class GEPA(Teleprompter):
valset=valset,
adapter=adapter,
# Reflection-based configuration
- reflection_lm=(lambda x: self.reflection_lm(x)[0]) if self.reflection_lm is not None else None,
+ reflection_lm=(lambda x: adapter.stripped_lm_call(x)[0]) if self.reflection_lm is not None else None,
candidate_selection_strategy=self.candidate_selection_strategy,
skip_perfect_score=self.skip_perfect_score,
reflection_minibatch_size=self.reflection_minibatch_size,
diff --git a/dspy/teleprompt/gepa/gepa_utils.py b/dspy/teleprompt/gepa/gepa_utils.py
index 6f4fa09c2..c9fa3e18f 100644
--- a/dspy/teleprompt/gepa/gepa_utils.py
+++ b/dspy/teleprompt/gepa/gepa_utils.py
@@ -146,7 +146,7 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):
base_instruction = candidate[name]
dataset_with_feedback = reflective_dataset[name]
results[name] = InstructionProposalSignature.run(
- lm=(lambda x: reflection_lm(x)[0]),
+ lm=(lambda x: self.stripped_lm_call(x)[0]),
input_dict={
"current_instruction_doc": base_instruction,
"dataset_with_feedback": dataset_with_feedback,
@@ -431,6 +431,23 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):
return ret_d
+ # Always return strings from the LM outputs
+ # Even when it returns a dict with e.g., "text" and "reasoning" fields
+ def stripped_lm_call(self, x: str) -> list[str]:
+ raw_outputs = self.reflection_lm(x)
+ outputs = []
+ for raw_output in raw_outputs:
+ if type(raw_output) == str:
+ outputs.append(raw_output)
+ elif type(raw_output) == dict:
+ if "text" not in raw_output:
+ raise KeyError("Missing 'text' field in the output from the base LM!")
+ outputs.append(raw_output["text"])
+ else:
+ raise TypeError("Unexpected output type from the base LM! Expected str or dict")
+
+ return outputs
+
# TODO: Generic tool module optimization - pending DSPy trace lineage improvements
# Currently only ReAct modules are supported for tool optimization.
# Re-enable _update_candidate_tools when DSPy provides better tool→trace lineage.
diff --git a/dspy/utils/dummies.py b/dspy/utils/dummies.py
index fb96f2c8c..019f0fc08 100644
--- a/dspy/utils/dummies.py
+++ b/dspy/utils/dummies.py
@@ -67,12 +67,19 @@ class DummyLM(LM):
"""
- def __init__(self, answers: list[dict[str, Any]] | dict[str, dict[str, Any]], follow_examples: bool = False, adapter=None):
+ def __init__(
+ self,
+ answers: list[dict[str, Any]] | dict[str, dict[str, Any]],
+ follow_examples: bool = False,
+ reasoning: bool = False,
+ adapter=None,
+ ):
super().__init__("dummy", "chat", 0.0, 1000, True)
self.answers = answers
if isinstance(answers, list):
self.answers = iter(answers)
self.follow_examples = follow_examples
+ self.reasoning = reasoning
# Set adapter, defaulting to ChatAdapter
if adapter is None:
@@ -122,16 +129,23 @@ class DummyLM(LM):
kwargs = {**self.kwargs, **kwargs}
if self.follow_examples:
- outputs.append(self._use_example(messages))
+ current_output = self._use_example(messages)
elif isinstance(self.answers, dict):
- outputs.append(
- next(
- (format_answer_fields(v) for k, v in self.answers.items() if k in messages[-1]["content"]),
- "No more responses",
- )
+ current_output = next(
+ (format_answer_fields(v) for k, v in self.answers.items() if k in messages[-1]["content"]),
+ "No more responses",
)
else:
- outputs.append(format_answer_fields(next(self.answers, {"answer": "No more responses"})))
+ current_output = format_answer_fields(next(self.answers, {"answer": "No more responses"}))
+
+ # Mock reasoning
+ if self.reasoning:
+ current_output = {
+ "text": current_output,
+ "reasoning_content": "Some reasoning",
+ }
+ # Store the output
+ outputs.append(current_output)
# Logging, with removed api key & where `cost` is None on cache hit.
kwargs = {k: v for k, v in kwargs.items() if not k.startswith("api_")}
diff --git a/tests/teleprompt/test_gepa_instruction_proposer.py b/tests/teleprompt/test_gepa_instruction_proposer.py
index 56af5e207..22c88f578 100644
--- a/tests/teleprompt/test_gepa_instruction_proposer.py
+++ b/tests/teleprompt/test_gepa_instruction_proposer.py
@@ -1,6 +1,9 @@
+import logging
from dataclasses import dataclass
from typing import Any
+import pytest
+
import dspy
from dspy.teleprompt.gepa import instruction_proposal
from dspy.utils.dummies import DummyLM
@@ -297,7 +300,8 @@ def test_image_serialization_into_strings():
)
-def test_default_proposer():
[email protected]("reasoning", [True, False])
+def test_default_proposer(reasoning: bool, caplog):
student = dspy.Predict("image -> label")
image = dspy.Image("https://picsum.photos/id/237/200/300")
@@ -332,7 +336,8 @@ def test_default_proposer():
{"improved_instruction": "Consider contextual clues in the image"},
{"improved_instruction": "Analyze shape, color, and texture patterns"},
{"improved_instruction": "Look for distinguishing characteristics"},
- ]
+ ],
+ reasoning=reasoning,
)
gepa = dspy.GEPA(
@@ -341,7 +346,19 @@ def test_default_proposer():
reflection_lm=reflection_lm,
)
- gepa.compile(student, trainset=examples, valset=examples)
+ with caplog.at_level(logging.INFO, logger="dspy.teleprompt.gepa.gepa"):
+ # Let logs propagate up to root because gepa uses try-catch and logs the error
+ # https://github.com/gepa-ai/gepa/blob/1b5eff5133be1015210e0512953c25a4b85ad454/src/gepa/proposer/reflective_mutation/reflective_mutation.py#L128
+ dspy_logger = logging.getLogger("dspy")
+ original_propagate = dspy_logger.propagate
+ dspy_logger.propagate = True
+
+ gepa.compile(student, trainset=examples, valset=examples)
+
+ dspy_logger.propagate = original_propagate
+
+ # Check that no internal GEPA reflection errors occured
+ assert "Exception during reflection/proposal" not in caplog.text
assert len(lm.history) > 0, "LM should have been called"
assert len(reflection_lm.history) > 0, "Reflection LM should have been called"