DSPy: The framework for programming—not prompting—language models
Python
feat(gepa): add code_proposer hook for custom dspy.Flex code proposals (#10212)
Drew Breunigf70d08a5b934
diff --git a/docs/docs/api/optimizers/GEPA/GEPA_Advanced.md b/docs/docs/api/optimizers/GEPA/GEPA_Advanced.mdindex 39ba410bc..9e8572fe1 100644--- a/docs/docs/api/optimizers/GEPA/GEPA_Advanced.md+++ b/docs/docs/api/optimizers/GEPA/GEPA_Advanced.md@@ -320,6 +320,82 @@ gepa = dspy.GEPA(- **Mind data serialization**: Serializing everything to strings might not be ideal - handle complex input types (like `dspy.Image`) by maintaining their structure for better LM processing- **Test thoroughly**: Test your custom proposer with representative failure cases+## Custom Code Proposers++### What is code_proposer?++`code_proposer` lets you supply your own function for rewriting the source code of a [`dspy.Flex`](../../../diving-deeper/flex.md) submodule during GEPA optimization. GEPA calls it each reflection round with the current source and the examples it ran on, and it returns a revised `dspy.Module` class.++DSPy's GEPA adapter sorts the optimizable parts of a program into two kinds of component. A **code component** is a `Flex` submodule, and its optimizable value is a whole `dspy.Module` source. An **instruction component** is any other predictor, and its value is an instruction string. `code_proposer` replaces the default proposer for code components, and `instruction_proposer` replaces it for instruction components. You can set either one without the other.++### The contract++A code proposer is a callable taking five keyword arguments:++| Argument | Meaning |+|---|---|+| `candidate` | A dict keyed by component name. Each value is that component's current value: the module source for a `Flex`, or the instruction string for an ordinary predictor. |+| `reflective_dataset` | A dict keyed by component name. Each value is the list of reflective records for that component from this round's minibatch. Each record is a dict with `Inputs`, `Generated Outputs`, and `Feedback`. |+| `components_to_update` | A list of the component names to rewrite this round, filtered to `Flex` submodules. |+| `task_descriptions` | A dict keyed by component name. Each value is a text rendering of that `Flex`'s signature: its name, objective, and input and output fields. |+| `context_blurbs` | A dict keyed by component name. Each value is a text block listing the tools passed to that `Flex` and the sandbox rules for using them. |++Note that `candidate` carries **every** component, including instruction components you aren't being asked to touch. `reflective_dataset` covers only the components the component selector picked this round, and omits a code component that produced no records. `components_to_update` is the authoritative list; use `reflective_dataset.get(name, [])` rather than indexing.++A code proposer returns a dict keyed by component name. Each value is the **complete replacement source** for that component. The source is one `dspy.Module` subclass that defines `forward`. An `__init__` is optional and is needed only if the module constructs predictors. Do not return a patch or a partial class.++Four things to know:++- **Records are whole-program, not per-predictor.** A `Flex`'s own predictors are part of what gets rewritten, so its reflective records hold the module's inputs, its final prediction, and the metric feedback, under the keys `Inputs`, `Generated Outputs`, and `Feedback`. Every example in the minibatch is included, not just the low-scoring ones; GEPA skips reflection only when the whole minibatch scores perfectly.+- **Strip markdown fences.** Whatever you return is bound as source verbatim. The built-in proposer strips fences from the LM's output; a fenced string returned from yours raises `SyntaxError` when GEPA binds it.+- **You own your failures.** The built-in proposer falls back to the original source when a proposal fails (except LM errors, which propagate). A custom proposer that raises propagates unconditionally — return `candidate[name]` unchanged if you want the same fallback.+- **A bad proposal is safe, just wasteful.** Source that doesn't parse is scored at the failure score and the search continues; it costs a step, not the run.++Your proposer runs inside the `reflection_lm` context, so a bare `dspy.Predict` inside it uses the reflection LM with no extra wiring. To use a different model, wrap your calls in `dspy.context(lm=...)`. Note that `code_proposer` does not by itself satisfy GEPA's reflection-provider requirement: you still need to pass `reflection_lm` (or an `instruction_proposer`).++### Example++````python+import dspy++class ProposeCode(dspy.Signature):+ """Rewrite the module to fix the observed failures."""+ task_description: str = dspy.InputField()+ current_source: str = dspy.InputField()+ failures: str = dspy.InputField()+ revised_source: str = dspy.OutputField(desc="One complete dspy.Module subclass.")++def _unfence(src):+ src = src.strip()+ if src.startswith("```"): # drop a ```python ... ``` wrapper+ src = src.split("\n", 1)[-1].rsplit("```", 1)[0]+ return src.strip()++def my_code_proposer(*, candidate, reflective_dataset, components_to_update,+ task_descriptions, context_blurbs):+ propose = dspy.Predict(ProposeCode)+ proposals = {}+ for name in components_to_update:+ failures = "\n\n".join(+ f"Inputs: {r['Inputs']}\nOutputs: {r['Generated Outputs']}\nFeedback: {r['Feedback']}"+ for r in reflective_dataset.get(name, [])+ )+ out = propose(+ task_description=task_descriptions.get(name, name),+ current_source=candidate[name],+ failures=failures,+ )+ proposals[name] = _unfence(out.revised_source)+ return proposals++gepa = dspy.GEPA(+ metric=my_metric,+ reflection_lm=dspy.LM(model="gpt-5"),+ code_proposer=my_code_proposer,+ auto="medium",+)+````+## Custom Component Selection### What is component_selector?diff --git a/docs/docs/diving-deeper/flex.md b/docs/docs/diving-deeper/flex.mdindex c47830733..5b7059019 100644--- a/docs/docs/diving-deeper/flex.md+++ b/docs/docs/diving-deeper/flex.md@@ -16,7 +16,7 @@ You construct `Flex` from any `dspy.Signature`, and it's immediately runnable. W### 3. GEPA discovers `Flex` by type and optimizes code instead of text-When GEPA compiles a program, it enumerates the `Flex` submodules and splits its work: each `Flex` becomes a **code component**, every other predictor stays an **instruction component**. Code components are seeded with their current `module_src` and evolved by a dedicated code proposer; instruction components are seeded with their current instructions and evolved by GEPA's usual instruction proposer. A custom `instruction_proposer` replaces the instruction proposer only; code components stay on the code proposer.+When GEPA compiles a program, it enumerates the `Flex` submodules and splits its work: each `Flex` becomes a **code component**, every other predictor stays an **instruction component**. Code components are seeded with their current `module_src` and evolved by a dedicated code proposer; instruction components are seeded with their current instructions and evolved by GEPA's usual instruction proposer. Each side has its own override: a custom `instruction_proposer` replaces the instruction proposer, a custom `code_proposer` replaces the code proposer, and whichever you leave unset keeps its default.### 4. The code proposer reflects on whole-program behaviordiff --git a/docs/docs/diving-deeper/gepa-in-depth.md b/docs/docs/diving-deeper/gepa-in-depth.mdindex eaae78034..730d04e3a 100644--- a/docs/docs/diving-deeper/gepa-in-depth.md+++ b/docs/docs/diving-deeper/gepa-in-depth.md@@ -62,7 +62,7 @@ Grouped by what you’re trying to do.### The optimizer-**`dspy.GEPA(metric, *, auto=None, max_full_evals=None, max_metric_calls=None, reflection_minibatch_size=3, candidate_selection_strategy="pareto", reflection_lm=None, skip_perfect_score=True, add_format_failure_as_feedback=False, instruction_proposer=None, component_selector="round_robin", use_merge=True, max_merge_invocations=5, num_threads=None, failure_score=0.0, perfect_score=1.0, log_dir=None, track_stats=False, use_wandb=False, use_mlflow=False, seed=0, ...)`**+**`dspy.GEPA(metric, *, auto=None, max_full_evals=None, max_metric_calls=None, reflection_minibatch_size=3, candidate_selection_strategy="pareto", reflection_lm=None, skip_perfect_score=True, add_format_failure_as_feedback=False, instruction_proposer=None, code_proposer=None, component_selector="round_robin", use_merge=True, max_merge_invocations=5, num_threads=None, failure_score=0.0, perfect_score=1.0, log_dir=None, track_stats=False, use_wandb=False, use_mlflow=False, seed=0, ...)`**Takes a feedback-shaped metric, a budget (exactly one of `auto` / `max_full_evals` / `max_metric_calls`), and a `reflection_lm` (defaults to the globally-configured LM — you’ll often want to pass a stronger one). `candidate_selection_strategy="current_best"` switches off Pareto sampling and turns GEPA into greedy local search. `failure_score` is the score assigned when the metric raises; `perfect_score` is the threshold for `skip_perfect_score`.@@ -96,6 +96,9 @@ Default `3`. Larger minibatches give the proposer more context (better proposals**`instruction_proposer`** — custom proposer hookA callable matching the `gepa.ProposalFn` protocol: takes a `{predictor_name: current_instruction}` dict, a reflective dataset of low-scoring examples, and a list of components to update; returns a new `{predictor_name: new_instruction}` dict. Override when the default proposer doesn’t handle your modality (signatures with `dspy.Image` fields, say) or when you want domain-specific constraints on the instructions.+**`code_proposer`** — custom proposer hook for `dspy.Flex` code components+The code-side counterpart. Receives the same `candidate` and `reflective_dataset` as `instruction_proposer`, plus two per-component maps: `task_descriptions` (the component's signature — name, objective, and input/output fields) and `context_blurbs` (the tools in scope and the sandbox rules for using them). Returns a full replacement `dspy.Module` source per component. Only `Flex` submodules route to it, so it does nothing on programs without them. See [Custom Code Proposers](../api/optimizers/GEPA/GEPA_Advanced.md#custom-code-proposers).+### Population dynamics**`candidate_selection_strategy`** — `"pareto"` (default) or `"current_best"`diff --git a/dspy/teleprompt/gepa/gepa.py b/dspy/teleprompt/gepa/gepa.pyindex 60f2fec26..8282ccb52 100644--- a/dspy/teleprompt/gepa/gepa.py+++ b/dspy/teleprompt/gepa/gepa.py@@ -11,7 +11,13 @@ from gepa.proposer.reflective_mutation.base import ReflectionComponentSelectorfrom dspy.clients.lm import LMfrom dspy.primitives import Example, Module, Prediction-from dspy.teleprompt.gepa.gepa_utils import DspyAdapter, DSPyTrace, PredictorFeedbackFn, ScoreWithFeedback+from dspy.teleprompt.gepa.gepa_utils import (+ CodeProposalFn,+ DspyAdapter,+ DSPyTrace,+ PredictorFeedbackFn,+ ScoreWithFeedback,+)from dspy.teleprompt.teleprompt import Teleprompterfrom dspy.utils.annotation import experimental@@ -286,6 +292,23 @@ class GEPA(Teleprompter):Note: When both instruction_proposer and reflection_lm are set, the instruction_proposer is calledin the reflection_lm context. However, reflection_lm is optional when using a custom instruction_proposer.Custom instruction proposers can invoke their own LLMs if needed.+ code_proposer: Optional custom proposer for `dspy.Flex` code components, implementing the+ `CodeProposalFn` protocol from `dspy.teleprompt.gepa.gepa_utils`.+ **Default: None** - Uses the built-in code proposer, which rewrites each Flex+ submodule's full `module_src` from the failing examples and feedback.++ A custom code proposer is called once per reflection round with the code components to+ update, the current candidate, the reflective dataset, and per-component task+ descriptions (the rendered Flex signature) and context blurbs (available tools and+ style notes). It must return a complete replacement `dspy.Module` subclass source per+ component. It is invoked inside the reflection_lm context, so predictors it creates+ use the reflection LM unless it selects a different one with `dspy.context(lm=...)`.+ Unlike instruction_proposer, it does not satisfy the requirement for a reflection+ provider: GEPA still requires reflection_lm or instruction_proposer to be set.++ Only Flex components are routed to it; regular predictors keep going to+ instruction_proposer (or the default instruction proposer). This parameter has no+ effect on programs without `dspy.Flex` submodules.component_selector: Custom component selector implementing the [ReflectionComponentSelector](https://github.com/gepa-ai/gepa/blob/main/src/gepa/proposer/reflective_mutation/base.py) protocol,or a string specifying a built-in selector strategy. Controls which components (predictors) are selectedfor optimization at each iteration. Defaults to 'round_robin' strategy which cycles through components@@ -391,6 +414,7 @@ class GEPA(Teleprompter):skip_perfect_score: bool = True,add_format_failure_as_feedback: bool = False,instruction_proposer: "ProposalFn | None" = None,+ code_proposer: "CodeProposalFn | None" = None,component_selector: "ReflectionComponentSelector | str" = "round_robin",# Merge-based configurationuse_merge: bool = True,@@ -474,6 +498,7 @@ class GEPA(Teleprompter):self.seed = seedself.custom_instruction_proposer = instruction_proposer+ self.custom_code_proposer = code_proposerself.component_selector = component_selectorself.gepa_kwargs = gepa_kwargs or {}@@ -619,6 +644,7 @@ class GEPA(Teleprompter):rng=rng,reflection_lm=self.reflection_lm,custom_instruction_proposer=self.custom_instruction_proposer,+ custom_code_proposer=self.custom_code_proposer,warn_on_score_mismatch=self.warn_on_score_mismatch,reflection_minibatch_size=self.reflection_minibatch_size,)diff --git a/dspy/teleprompt/gepa/gepa_utils.py b/dspy/teleprompt/gepa/gepa_utils.pyindex 183478978..3276f751d 100644--- a/dspy/teleprompt/gepa/gepa_utils.py+++ b/dspy/teleprompt/gepa/gepa_utils.py@@ -54,6 +54,25 @@ Each example contains the predictor inputs, generated outputs, and feedback from"""+class CodeProposalFn(Protocol):+ """Custom proposer for dspy.Flex code components.++ The code-component counterpart of gepa's ProposalFn: called with the code components to+ update plus the per-component task descriptions (rendered Flex signatures) and context+ blurbs (available tools and style notes), under the reflection LM's context. Returns a+ full replacement module source (one dspy.Module subclass) per component.+ """++ def __call__(+ self,+ candidate: dict[str, str],+ reflective_dataset: dict[str, list[dict[str, Any]]],+ components_to_update: list[str],+ task_descriptions: dict[str, str],+ context_blurbs: dict[str, str],+ ) -> dict[str, str]: ...++class ScoreWithFeedback(Prediction):score: floatfeedback: str@@ -104,6 +123,7 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):rng: random.Random | None = None,reflection_lm=None,custom_instruction_proposer: "ProposalFn | None" = None,+ custom_code_proposer: "CodeProposalFn | None" = None,warn_on_score_mismatch: bool = True,reflection_minibatch_size: int | None = None,):@@ -116,6 +136,7 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):self.rng = rng or random.Random(0)self.reflection_lm = reflection_lmself.custom_instruction_proposer = custom_instruction_proposer+ self.custom_code_proposer = custom_code_proposerself.warn_on_score_mismatch = warn_on_score_mismatchself.reflection_minibatch_size = reflection_minibatch_sizeself._warned_custom_proposer_skips_code = False@@ -133,23 +154,37 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):) -> dict[str, str]:reflection_lm = self.reflection_lm or dspy.settings.lm- # dspy.Flex code components are rewritten by the code proposer.+ # dspy.Flex code components are rewritten by the code proposer. A custom code proposer+ # overrides the built-in one, mirroring how custom_instruction_proposer overrides the+ # default instruction proposer below.results: dict[str, str] = {}code_keys = [c for c in components_to_update if c in self._flex_paths]if code_keys:- results.update(- propose_code(- code_keys, candidate, reflective_dataset,- self._flex_task_descriptions, self._flex_context_blurbs, reflection_lm,+ if self.custom_code_proposer:+ with dspy.context(lm=reflection_lm):+ results.update(+ self.custom_code_proposer(+ candidate=candidate,+ reflective_dataset=reflective_dataset,+ components_to_update=code_keys,+ task_descriptions=self._flex_task_descriptions,+ context_blurbs=self._flex_context_blurbs,+ )+ )+ else:+ results.update(+ propose_code(+ code_keys, candidate, reflective_dataset,+ self._flex_task_descriptions, self._flex_context_blurbs, reflection_lm,+ ))- )components_to_update = [c for c in components_to_update if c not in self._flex_paths]if not components_to_update:return results# A custom proposer overrides the default *instruction* proposer only.if self.custom_instruction_proposer:- if code_keys and not self._warned_custom_proposer_skips_code:+ if code_keys and not self.custom_code_proposer and not self._warned_custom_proposer_skips_code:logger.warning("A custom instruction_proposer is set, but %d dspy.Flex code component(s) are ""being optimized. The custom proposer handles instruction components only; the "diff --git a/tests/flex/test_flex_gepa.py b/tests/flex/test_flex_gepa.pyindex 861d9344f..a346167a0 100644--- a/tests/flex/test_flex_gepa.py+++ b/tests/flex/test_flex_gepa.py@@ -407,6 +407,102 @@ def test_code_proposer_bad_proposal_keeps_original() -> None:assert out == {"self": original}+# --- adapter: a custom code proposer overrides the built-in one ---------------+++def test_custom_code_proposer_overrides_builtin_and_receives_contract() -> None:+ captured = {}++ def code_proposer(*, candidate, reflective_dataset, components_to_update, task_descriptions, context_blurbs):+ captured.update(+ candidate=candidate,+ reflective_dataset=reflective_dataset,+ components_to_update=components_to_update,+ task_descriptions=task_descriptions,+ context_blurbs=context_blurbs,+ )+ return dict.fromkeys(components_to_update, SIMPLE_MODULE)++ student = dspy.Flex(Echo)+ adapter = DspyAdapter(+ student_module=student,+ metric_fn=_metric,+ feedback_map={},+ reflection_lm=DummyLM([]), # empty: any call through the built-in proposer would fail+ custom_code_proposer=code_proposer,+ )+ candidate = {"self": student.module_src}+ reflective = {"self": [{"Inputs": {"q": "x"}, "Generated Outputs": "wrong", "Feedback": "bad"}]}++ out = adapter.propose_new_texts(candidate, reflective, ["self"])++ assert out == {"self": SIMPLE_MODULE}+ assert captured["components_to_update"] == ["self"]+ assert captured["candidate"] == candidate+ assert captured["reflective_dataset"] == reflective+ assert "self" in captured["task_descriptions"]+ assert "self" in captured["context_blurbs"]+++def test_custom_code_proposer_runs_in_reflection_lm_context() -> None:+ seen = {}+ reflection = DummyLM([])++ def code_proposer(*, candidate, reflective_dataset, components_to_update, task_descriptions, context_blurbs):+ seen["lm"] = dspy.settings.lm+ return dict.fromkeys(components_to_update, SIMPLE_MODULE)++ student = dspy.Flex(Echo)+ adapter = DspyAdapter(+ student_module=student,+ metric_fn=_metric,+ feedback_map={},+ reflection_lm=reflection,+ custom_code_proposer=code_proposer,+ )+ adapter.propose_new_texts({"self": student.module_src}, {"self": []}, ["self"])+ assert seen["lm"] is reflection+++def test_no_skip_warning_when_custom_code_proposer_handles_code(caplog) -> None:+ """The 'custom instruction_proposer skips code components' warning exists because those+ components would otherwise fall through to the built-in code proposer silently. With a+ custom code proposer installed, nothing is skipped, so the warning must not fire."""++ class Prog(dspy.Module):+ def __init__(self):+ super().__init__()+ self.flex = dspy.Flex(Echo)+ self.sibling = dspy.Predict("x -> y")++ def forward(self, **kwargs):+ return self.flex(**kwargs)++ def instruction_proposer(*, candidate, reflective_dataset, components_to_update):+ return dict.fromkeys(components_to_update, "new instruction")++ def code_proposer(*, candidate, reflective_dataset, components_to_update, task_descriptions, context_blurbs):+ return dict.fromkeys(components_to_update, SIMPLE_MODULE)++ prog = Prog()+ adapter = DspyAdapter(+ student_module=prog,+ metric_fn=_metric,+ feedback_map={},+ reflection_lm=DummyLM([]),+ custom_instruction_proposer=instruction_proposer,+ custom_code_proposer=code_proposer,+ )+ candidate = {"flex": prog.flex.module_src, "sibling": "old instruction"}+ reflective = {"flex": [], "sibling": []}++ with caplog.at_level("WARNING"):+ out = adapter.propose_new_texts(candidate, reflective, ["flex", "sibling"])++ assert out == {"flex": SIMPLE_MODULE, "sibling": "new instruction"}+ assert not any("code component" in r.message for r in caplog.records)++# --- GEPA.compile: seed mixes code + instruction components ------------------@@ -448,6 +544,25 @@ def test_gepa_seed_mixes_code_and_instruction_components(monkeypatch) -> None:assert not any(k.startswith("flex.") for k in seed)+def test_gepa_compile_threads_code_proposer_to_adapter(monkeypatch) -> None:+ captured = {}++ def fake_optimize(**kwargs):+ captured["adapter"] = kwargs["adapter"]+ return _FakeResult(best_candidate=kwargs["seed_candidate"])++ monkeypatch.setattr("gepa.optimize", fake_optimize)++ def code_proposer(*, candidate, reflective_dataset, components_to_update, task_descriptions, context_blurbs):+ return dict.fromkeys(components_to_update, SIMPLE_MODULE)++ optimizer = dspy.GEPA(metric=_metric, reflection_lm=DummyLM([]), max_metric_calls=10, code_proposer=code_proposer)+ ex = dspy.Example(q="x", a="y").with_inputs("q")+ optimizer.compile(dspy.Flex(Echo), trainset=[ex], valset=[ex])++ assert captured["adapter"].custom_code_proposer is code_proposer++# --- DspyGEPAResult.to_dict: candidates keep their code components -----------