Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

fix(gepa): Remove enable_tool_optimization feature (#9223)

Juyoung Lee73b2624943a5
diff --git a/docs/docs/api/optimizers/GEPA/overview.md b/docs/docs/api/optimizers/GEPA/overview.md
index 4bca3b1cc..0125702be 100644
--- a/docs/docs/api/optimizers/GEPA/overview.md
+++ b/docs/docs/api/optimizers/GEPA/overview.md
@@ -117,12 +117,6 @@ Practical Recipe for GEPA-Friendly Feedback:
- **Multi-Objective Tasks** (e.g., PUPA): Decompose aggregate scores to reveal contributions from each objective, highlighting tradeoffs (e.g., quality vs. privacy).
- **Stacked Pipelines** (e.g., code generation: parse → compile → run → profile → evaluate): Expose stage-specific failures; natural-language traces often suffice for LLM self-correction.
-## Tool Optimization with GEPA
-
-When `enable_tool_optimization=True`, GEPA jointly optimizes `dspy.ReAct` modules with the tools - GEPA updates predictor instructions and tool descriptions/argument descriptions together, based on execution traces and feedback, instead of keeping tool behavior fixed.
-
-For details, examples, and the underlying design (tool discovery, naming requirements, and interaction with custom instruction proposers), see [Tool Optimization](GEPA_Advanced.md#tool-optimization).
-
## Custom Instruction Proposal
For advanced customization of GEPA's instruction proposal mechanism, including custom instruction proposers and component selectors, see [Advanced Features](GEPA_Advanced.md).
diff --git a/dspy/teleprompt/gepa/gepa.py b/dspy/teleprompt/gepa/gepa.py
index d0427ffeb..cb752150a 100644
--- a/dspy/teleprompt/gepa/gepa.py
+++ b/dspy/teleprompt/gepa/gepa.py
@@ -1,5 +1,4 @@
import inspect
-import json
import logging
import random
from dataclasses import dataclass
@@ -10,15 +9,8 @@ from gepa.core.adapter import ProposalFn
from gepa.proposer.reflective_mutation.base import ReflectionComponentSelector
from dspy.clients.lm import LM
-from dspy.predict.react import ReAct
from dspy.primitives import Example, Module, Prediction
-from dspy.teleprompt.gepa.gepa_utils import (
- TOOL_MODULE_PREFIX,
- DspyAdapter,
- DSPyTrace,
- PredictorFeedbackFn,
- ScoreWithFeedback,
-)
+from dspy.teleprompt.gepa.gepa_utils import DspyAdapter, DSPyTrace, PredictorFeedbackFn, ScoreWithFeedback
from dspy.teleprompt.teleprompt import Teleprompter
from dspy.utils.annotation import experimental
@@ -283,11 +275,6 @@ class GEPA(Teleprompter):
warn_on_score_mismatch: GEPA (currently) expects the metric to return the same module-level score when
called with and without the pred_name. This flag (defaults to True) determines whether a warning is
raised if a mismatch in module-level and predictor-level score is detected.
- enable_tool_optimization: Whether to enable joint optimization of dspy.ReAct modules.
- When enabled, GEPA jointly optimizes predictor instructions and tool descriptions together
- for dspy.ReAct modules. See the
- [Tool Optimization guide](https://dspy.ai/api/optimizers/GEPA/GEPA_Advanced/#tool-optimization)
- for details on when to use this feature and how it works. Default is False.
seed: The random seed to use for reproducibility. Default is 0.
gepa_kwargs: (Optional) Additional keyword arguments to pass directly to [gepa.optimize](https://github.com/gepa-ai/gepa/blob/main/src/gepa/api.py).
Useful for accessing advanced GEPA features not directly exposed through DSPy's GEPA interface.
@@ -371,7 +358,6 @@ class GEPA(Teleprompter):
wandb_init_kwargs: dict[str, Any] | None = None,
track_best_outputs: bool = False,
warn_on_score_mismatch: bool = True,
- enable_tool_optimization: bool = False,
use_mlflow: bool = False,
# Reproducibility
seed: int | None = 0,
@@ -429,7 +415,6 @@ class GEPA(Teleprompter):
self.wandb_api_key = wandb_api_key
self.wandb_init_kwargs = wandb_init_kwargs
self.warn_on_score_mismatch = warn_on_score_mismatch
- self.enable_tool_optimization = enable_tool_optimization
self.use_mlflow = use_mlflow
if track_best_outputs:
@@ -443,80 +428,6 @@ class GEPA(Teleprompter):
self.component_selector = component_selector
self.gepa_kwargs = gepa_kwargs or {}
- def _build_seed_candidate(self, student: Module) -> dict[str, str]:
- """
- Build the seed candidate configuration from the student module.
-
- For ReAct modules (when tool optimization is enabled), creates a JSON config containing:
- - react predictor instructions
- - extract predictor instructions
- - tool descriptions and argument descriptions
-
- For regular predictors, uses their signature instructions directly.
-
- Returns:
- A dictionary mapping component names to their text representations (instructions or JSON configs).
- """
- seed_candidate = {}
- claimed_predictor_names = set()
-
- # Process ReAct modules when tool optimization is enabled
- if self.enable_tool_optimization:
- for module_path, module in student.named_sub_modules():
- if not isinstance(module, ReAct):
- continue
-
- # Verify DSPy's two-predictor ReAct design
- assert hasattr(module, "extract") and hasattr(module.extract, "predict"), (
- f"ReAct module '{module_path}' missing extract.predict - DSPy design may have changed"
- )
-
- # Get predictor names via object identity
- extract_predictor = module.extract.predict
- react_predictor = module.react
- extract_predictor_name = None
- react_predictor_name = None
- for name, pred in student.named_predictors():
- if pred is extract_predictor:
- extract_predictor_name = name
- elif pred is react_predictor:
- react_predictor_name = name
-
- # Use extract.predict as the key since it is the target predictor for feedback lookup
- module_key = f"{TOOL_MODULE_PREFIX}:{extract_predictor_name}"
-
- # Build JSON config with dynamic predictor names as keys
- config = {
- react_predictor_name: react_predictor.signature.instructions,
- extract_predictor_name: extract_predictor.signature.instructions,
- "tools": {
- tool_name: {"desc": tool.desc, "args": tool.args}
- for tool_name, tool in module.tools.items()
- if tool_name != "finish" # Skip the built-in finish tool
- },
- }
-
- seed_candidate[module_key] = json.dumps(config, indent=2)
- # Track predictor names that are part of ReAct modules
- claimed_predictor_names.add(react_predictor_name)
- claimed_predictor_names.add(extract_predictor_name)
- else:
- # Warn if ReAct modules found but tool optimization disabled
- for module_path, module in student.named_sub_modules():
- if isinstance(module, ReAct):
- logger.info(
- f"Detected ReAct module at '{module_path}'. Consider using "
- "`enable_tool_optimization=True` to jointly optimize react instructions, "
- "extract instructions, tool descriptions, and tool argument descriptions."
- )
-
- # Add individual predictors that aren't part of ReAct module configs
- for name, pred in student.named_predictors():
- if name not in claimed_predictor_names:
- seed_candidate[name] = pred.signature.instructions
-
- return seed_candidate
-
def auto_budget(
self, num_preds, num_candidates, valset_size: int, minibatch_size: int = 35, full_eval_steps: int = 5
) -> int:
@@ -640,12 +551,11 @@ class GEPA(Teleprompter):
reflection_lm=self.reflection_lm,
custom_instruction_proposer=self.custom_instruction_proposer,
warn_on_score_mismatch=self.warn_on_score_mismatch,
- enable_tool_optimization=self.enable_tool_optimization,
reflection_minibatch_size=self.reflection_minibatch_size,
)
- # Build the seed candidate configuration
- seed_candidate = self._build_seed_candidate(student)
+ # Build the seed candidate: map each predictor name to its current instruction
+ seed_candidate = {name: pred.signature.instructions for name, pred in student.named_predictors()}
gepa_result: GEPAResult = optimize(
seed_candidate=seed_candidate,
diff --git a/dspy/teleprompt/gepa/gepa_utils.py b/dspy/teleprompt/gepa/gepa_utils.py
index c9fa3e18f..dae7157fe 100644
--- a/dspy/teleprompt/gepa/gepa_utils.py
+++ b/dspy/teleprompt/gepa/gepa_utils.py
@@ -1,4 +1,3 @@
-import json
import logging
import random
from typing import Any, Callable, Protocol, TypedDict
@@ -11,18 +10,13 @@ import dspy
from dspy.adapters.chat_adapter import ChatAdapter
from dspy.adapters.types import History
from dspy.adapters.types.base_type import Type
-from dspy.adapters.types.tool import Tool
from dspy.evaluate import Evaluate
-from dspy.primitives import Example, Module, Prediction
+from dspy.primitives import Example, Prediction
from dspy.teleprompt.bootstrap_trace import FailedPrediction, TraceData
logger = logging.getLogger(__name__)
-# Constants for module optimization
-TOOL_MODULE_PREFIX = "tool_module"
-
-
class LoggerAdapter:
def __init__(self, logger: logging.Logger):
self.logger = logger
@@ -93,7 +87,6 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):
reflection_lm=None,
custom_instruction_proposer: "ProposalFn | None" = None,
warn_on_score_mismatch: bool = True,
- enable_tool_optimization: bool = False,
reflection_minibatch_size: int | None = None,
):
self.student = student_module
@@ -106,7 +99,6 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):
self.reflection_lm = reflection_lm
self.custom_instruction_proposer = custom_instruction_proposer
self.warn_on_score_mismatch = warn_on_score_mismatch
- self.enable_tool_optimization = enable_tool_optimization
self.reflection_minibatch_size = reflection_minibatch_size
def propose_new_texts(
@@ -125,129 +117,31 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):
components_to_update=components_to_update,
)
- # Otherwise, route to appropriate proposers
- # Separate into two categories: tool-using modules (ReAct) vs regular instructions
- # TODO: Add generic tool module support when DSPy trace lineage is improved
- tool_components = []
- instruction_components = []
-
- for c in components_to_update:
- if c.startswith(TOOL_MODULE_PREFIX):
- tool_components.append(c)
- else:
- instruction_components.append(c)
-
results: dict[str, str] = {}
with dspy.context(lm=reflection_lm):
- # Handle regular instruction components
- if instruction_components:
- for name in instruction_components:
- base_instruction = candidate[name]
- dataset_with_feedback = reflective_dataset[name]
- results[name] = InstructionProposalSignature.run(
- lm=(lambda x: self.stripped_lm_call(x)[0]),
- input_dict={
- "current_instruction_doc": base_instruction,
- "dataset_with_feedback": dataset_with_feedback,
- },
- )["new_instruction"]
-
- # Handle ReAct modules
- if tool_components:
- from dspy.teleprompt.gepa.instruction_proposal import ToolProposer
-
- tool_proposer = ToolProposer()
- results.update(
- tool_proposer(
- candidate=candidate,
- reflective_dataset=reflective_dataset,
- components_to_update=tool_components,
- )
- )
+ for name in components_to_update:
+ base_instruction = candidate[name]
+ dataset_with_feedback = reflective_dataset[name]
+ results[name] = InstructionProposalSignature.run(
+ lm=(lambda x: self.stripped_lm_call(x)[0]),
+ input_dict={
+ "current_instruction_doc": base_instruction,
+ "dataset_with_feedback": dataset_with_feedback,
+ },
+ )["new_instruction"]
return results
def build_program(self, candidate: dict[str, str]):
new_prog = self.student.deepcopy()
- # Start with plain string instructions from candidate
- predictor_candidates = {k: v for k, v in candidate.items() if not k.startswith(TOOL_MODULE_PREFIX)}
-
- tool_candidates = {}
- if self.enable_tool_optimization:
- for key, value in candidate.items():
- if not key.startswith(TOOL_MODULE_PREFIX):
- continue
-
- config = json.loads(value)
-
- for pred_name, instruction in config.items():
- if isinstance(instruction, str):
- predictor_candidates[pred_name] = instruction
-
- tool_candidates.update(config.get("tools", {}))
-
- # Update predictor instructions
for name, pred in new_prog.named_predictors():
- if name in predictor_candidates:
- pred.signature = pred.signature.with_instructions(predictor_candidates[name])
-
- # Update tool descriptions
- if tool_candidates:
- self._update_tool_descriptions(new_prog, tool_candidates)
+ if name in candidate:
+ pred.signature = pred.signature.with_instructions(candidate[name])
return new_prog
- def _update_tool_descriptions(self, program: Module, tool_candidates: dict[str, Any]) -> None:
- all_tools = self._collect_tools(program)
-
- for tool_name, tool_config in tool_candidates.items():
- if tool_name not in all_tools:
- logger.warning(
- f"Skipping updates for tool:'{tool_name}' because it cannot be detected on the student program."
- )
- continue
-
- tool = all_tools[tool_name]
-
- # Update tool description if present.
- if tool_config.get("desc"):
- tool.desc = tool_config["desc"]
-
- # Update arg descriptions if present.
- args_schema = tool_config.get("args") or {}
- for arg_name, arg_schema in args_schema.items():
- if arg_schema.get("description") is not None:
- tool.args[arg_name]["description"] = arg_schema["description"]
-
- def _collect_tools(self, module: Module) -> dict[str, Tool]:
- """Recursively collect all Tool instances from a module and its sub-modules."""
- all_tools = {}
- visited = set()
-
- def _collect_from_attribute(attr_value):
- if isinstance(attr_value, Tool):
- all_tools[attr_value.name] = attr_value
- elif isinstance(attr_value, dspy.Module):
- _traverse(attr_value)
- elif isinstance(attr_value, list | dict):
- items = attr_value if isinstance(attr_value, list) else attr_value.values()
- for item in items:
- if isinstance(item, Tool):
- all_tools[item.name] = item
-
- def _traverse(current_module):
- if id(current_module) in visited or not hasattr(current_module, "__dict__"):
- return
- visited.add(id(current_module))
-
- for attr_value in current_module.__dict__.values():
- _collect_from_attribute(attr_value)
-
- _traverse(module)
- return all_tools
-
def evaluate(self, batch, candidate, capture_traces=False):
program = self.build_program(candidate)
callback_metadata = (
@@ -309,19 +203,13 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):
ret_d: dict[str, list[ReflectiveExample]] = {}
for pred_name in components_to_update:
- # Extract predictor name from component key
- if pred_name.startswith(TOOL_MODULE_PREFIX):
- target_name = pred_name.removeprefix(f"{TOOL_MODULE_PREFIX}:")
- else:
- target_name = pred_name
-
# Find the predictor object
module = None
for name, m in program.named_predictors():
- if name == target_name:
+ if name == pred_name:
module = m
break
- assert module is not None, f"Predictor not found: {target_name}"
+ assert module is not None, f"Predictor not found: {pred_name}"
# Create reflective examples from traces
items: list[ReflectiveExample] = []
@@ -400,8 +288,7 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):
d["Feedback"] = "Your output failed to parse. Follow this structure:\n" + structure_instruction
# d['score'] = self.failure_score
else:
- # Use actual predictor name for feedback lookup
- feedback_fn = self.feedback_map[target_name]
+ feedback_fn = self.feedback_map[pred_name]
fb = feedback_fn(
predictor_output=outputs,
predictor_inputs=inputs,
@@ -448,36 +335,3 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):
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.
- #
- # def _update_candidate_tools(self, candidate, program, trajectories) -> None:
- # """Extract dspy.Tool objects from traces for tool modules and update candidate["tools"]."""
- # ...
-
- # TODO: The current DSPyAdapter implementation uses the GEPA default propose_new_texts.
- # We can potentially override this, to use the instruction proposal similar to MIPROv2.
-
- # def propose_new_texts(
- # self,
- # candidate: Dict[str, str],
- # reflective_dataset: Dict[str, List[Dict[str, Any]]],
- # components_to_update: List[str]
- # ) -> Dict[str, str]:
- # if self.adapter.propose_new_texts is not None:
- # return self.adapter.propose_new_texts(candidate, reflective_dataset, components_to_update)
-
- # from .instruction_proposal import InstructionProposalSignature
- # new_texts: Dict[str, str] = {}
- # for name in components_to_update:
- # base_instruction = candidate[name]
- # dataset_with_feedback = reflective_dataset[name]
- # new_texts[name] = InstructionProposalSignature.run(
- # lm=self.reflection_lm,
- # input_dict={
- # "current_instruction_doc": base_instruction,
- # "dataset_with_feedback": dataset_with_feedback
- # }
- # )['new_instruction']
- # return new_texts
diff --git a/dspy/teleprompt/gepa/instruction_proposal.py b/dspy/teleprompt/gepa/instruction_proposal.py
index 19d3ac400..9a0e26d35 100644
--- a/dspy/teleprompt/gepa/instruction_proposal.py
+++ b/dspy/teleprompt/gepa/instruction_proposal.py
@@ -1,4 +1,3 @@
-import json
import logging
from typing import Any
@@ -314,184 +313,3 @@ class MultiModalInstructionProposer(ProposalFn):
updated_components[component_name] = new_instruction
return updated_components
-
-
-class GenerateImprovedToolModuleDescriptionsFromFeedback(dspy.Signature):
- """I provided an assistant with predictor instructions and tool descriptions,
- but its performance needs improvement based on the examples_with_feedback below.
-
- Your task is to propose better predictor instructions, tool descriptions, and tool argument descriptions that address the issues shown in these examples.
- Focus on reinforcing patterns that clearly improve the assistant's performance on similar tasks, rather than rewriting everything from scratch unless necessary.
- These components are progressively optimized - refine only what needs to change.
-
- Analyze the examples_with_feedback to identify success and failure patterns, and write improved instructions and descriptions at their appropriate level of abstraction and/or specificity,
- so that each layer plays a clear, complementary role without unnecessary repetition or verbosity unless redundancy clearly helps the assistant's performance.
- """
-
- current_predictor_instruction = dspy.InputField(desc="Current instruction guiding the predictor")
- current_tools = dspy.InputField(annotation=list[dspy.Tool], desc="Available tools with their complete schemas")
- examples_with_feedback = dspy.InputField(desc="Execution examples with feedback showing successes and failures")
-
- improved_predictor_instruction: str | None = dspy.OutputField(
- desc="Improved instruction for the predictor", default=None
- )
-
-
-class ToolProposer(ProposalFn):
- """Proposer for optimizing tool-using module configurations.
-
- Supports two types of modules:
- - Tool modules (1 predictor): Optimizes predictor instruction and tool descriptions
- - ReAct modules (2 predictors): Jointly optimizes react instruction, extract instruction, and tool descriptions
-
- Uses dynamic signature generation to create output fields for each tool and parameter,
- enabling the reflection LM to optimize all components cohesively based on execution feedback.
-
- This joint optimization approach allows the LM to see how instructions and tool descriptions
- work together, leading to more coherent improvements than optimizing each component separately.
- """
-
- def __call__(
- self,
- candidate: dict[str, str],
- reflective_dataset: dict[str, list[ReflectiveExample]],
- components_to_update: list[str],
- ) -> dict[str, str]:
- """Optimize tool-using module components.
-
- Args:
- candidate: Current component name -> JSON config mapping
- reflective_dataset: Component name -> list of reflective examples
- components_to_update: List of tool-using module component names to update
-
- Returns:
- dict: Mapping of component names to improved JSON configs
- """
-
- updated_components = {}
-
- for module_key in components_to_update:
- if module_key not in candidate or module_key not in reflective_dataset:
- logger.debug(
- f"Skipping {module_key}: not in candidate={module_key not in candidate}, not in "
- "reflective_dataset={module_key not in reflective_dataset}"
- )
- continue
- current_module_config = json.loads(candidate[module_key])
-
- # Predictor keys: ReAct has 2 predictors (react + extract)
- predictor_keys = [k for k, v in current_module_config.items() if isinstance(v, str)]
- primary_predictor_key = predictor_keys[0]
- extract_predictor_key = predictor_keys[1] if len(predictor_keys) > 1 else None
-
- # Reconstruct Tool objects from JSON (func is placeholder since it can't be serialized)
- current_tools_dict = current_module_config.get("tools", {})
- tools_list = []
- for tool_name, tool_info in current_tools_dict.items():
- tool = dspy.Tool(
- func=lambda *args, **kwargs: None, # Placeholder - Tool requires Callable, but only schema is used
- name=tool_name,
- desc=tool_info.get("desc", ""),
- )
- tool.args = tool_info.get("args", {})
- tools_list.append(tool)
-
- # Build dynamic signature with tool-specific output fields
- signature = GenerateImprovedToolModuleDescriptionsFromFeedback
-
- for tool in tools_list:
- tool_name = tool.name
- tool_info = current_tools_dict[tool_name]
-
- signature = signature.append(
- f"improved_tool_{tool_name}_desc",
- dspy.OutputField(desc=f"Improved description of tool '{tool_name}'", default=None),
- )
-
- for arg_name in tool_info["args"].keys():
- signature = signature.append(
- f"improved_tool_{tool_name}_arg_{arg_name}_desc",
- dspy.OutputField(
- desc=f"Improved description of the argument '{arg_name}' of tool '{tool_name}'",
- default=None,
- ),
- )
-
- kwargs = {
- "current_predictor_instruction": current_module_config[primary_predictor_key],
- "current_tools": tools_list,
- "examples_with_feedback": self._format_examples(reflective_dataset[module_key]),
- }
- # If module has extract predictor, add extract fields
- if extract_predictor_key is not None:
- signature = signature.append(
- "current_extract_instruction", dspy.InputField(desc="Current instruction for extraction predictor")
- )
- signature = signature.append(
- "improved_extract_instruction",
- dspy.OutputField(desc="Improved instruction for extraction", default=None),
- )
- kwargs["current_extract_instruction"] = current_module_config[extract_predictor_key]
-
- propose_descriptions = dspy.Predict(signature)
- result = propose_descriptions(**kwargs)
-
- # Build improved config (reflection LM returns None to keep original, or new text)
- improved_module_config = {}
-
- if result.improved_predictor_instruction is not None:
- improved_module_config[primary_predictor_key] = result.improved_predictor_instruction
-
- if extract_predictor_key is not None and result.improved_extract_instruction is not None:
- improved_module_config[extract_predictor_key] = result.improved_extract_instruction
-
- improved_module_config["tools"] = {}
- for tool_name, tool_info in current_tools_dict.items():
- # Update tool description if LM proposed a change
- improved_tool_desc = getattr(result, f"improved_tool_{tool_name}_desc", None)
- if improved_tool_desc is not None:
- tool_info["desc"] = improved_tool_desc
-
- # Update arg descriptions if LM proposed changes
- for arg_name in tool_info["args"].keys():
- improved_tool_arg_desc = getattr(result, f"improved_tool_{tool_name}_arg_{arg_name}_desc", None)
- if improved_tool_arg_desc is not None:
- tool_info["args"][arg_name]["description"] = improved_tool_arg_desc
-
- improved_module_config["tools"][tool_name] = tool_info
-
- updated_components[module_key] = json.dumps(improved_module_config, indent=2)
-
- return updated_components
-
- def _format_examples(self, reflective_dataset: list[ReflectiveExample]) -> str:
- """Format reflective examples using GEPA's markdown structure."""
-
- def render_value(value, level=3):
- if isinstance(value, dict):
- s = ""
- for key, val in value.items():
- s += f"{'#' * level} {key}\n"
- s += render_value(val, min(level + 1, 6))
- if not value:
- s += "\n"
- return s
- if isinstance(value, (list, tuple)):
- s = ""
- for index, item in enumerate(value):
- s += f"{'#' * level} Item {index + 1}\n"
- s += render_value(item, min(level + 1, 6))
- if not value:
- s += "\n"
- return s
- return f"{str(value).strip()}\n\n"
-
- def convert_sample_to_markdown(sample, example_num):
- s = f"# Example {example_num}\n"
- for key, val in sample.items():
- s += f"## {key}\n"
- s += render_value(val, level=3)
- return s
-
- formatted_parts = [convert_sample_to_markdown(example, i + 1) for i, example in enumerate(reflective_dataset)]
- return "\n\n".join(formatted_parts)
diff --git a/tests/teleprompt/test_gepa_tool_optimization.py b/tests/teleprompt/test_gepa_tool_optimization.py
deleted file mode 100644
index 0c414e849..000000000
--- a/tests/teleprompt/test_gepa_tool_optimization.py
+++ /dev/null
@@ -1,353 +0,0 @@
-"""Tests for GEPA's tool optimization (ReAct modules).
-
-Test categories:
-1. Detection - Compile-time detection of dspy.ReAct modules
-2. Application - build_program applies optimized instructions and tool descriptions
-
-DSPy ReAct Design Note:
- DSPy's ReAct uses two predictors:
- - react: reasoning/acting loop
- - extract: structured output synthesis
-
- We optimize extract.predict as it's called once with the complete trajectory
- and produces all output fields.
-"""
-
-import json
-
-import gepa
-from gepa import optimize as gepa_optimize
-
-import dspy
-from dspy.teleprompt.gepa.gepa_utils import TOOL_MODULE_PREFIX, DspyAdapter
-from dspy.utils.dummies import DummyLM
-
-
-# Test tool fixtures
-def search(query: str) -> str:
- """Test search tool."""
- return f"Search: {query}"
-
-
-def calculate(expr: str) -> str:
- """Test calculator tool."""
- return str(eval(expr))
-
-
-def analyze(data: str) -> str:
- """Test analyzer tool."""
- return f"Analysis: {data}"
-
-
-def setup_seed_candidate_capture(monkeypatch):
- """Capture seed_candidate dict passed to gepa.optimize."""
- captured = {}
-
- def capture_optimize(seed_candidate, **kwargs):
- captured.update(seed_candidate)
- return gepa_optimize(seed_candidate=seed_candidate, **kwargs)
-
- monkeypatch.setattr(gepa, "optimize", capture_optimize)
- return captured
-
-
-def create_optimizer(task_responses, reflection_responses):
- """Create GEPA optimizer with explicit LM responses.
-
- Args:
- task_responses: List of dicts for task LM (e.g., [{"answer": "test"}])
- reflection_responses: List of dicts for reflection LM
-
- Returns:
- tuple: (optimizer, trainset)
- """
- task_lm = DummyLM(task_responses)
- reflection_lm = DummyLM(reflection_responses)
-
- dspy.settings.configure(lm=task_lm)
-
- optimizer = dspy.GEPA(
- metric=lambda example, pred, trace=None, pred_name=None, pred_trace=None: dspy.Prediction(score=0.5, feedback="ok"),
- reflection_lm=reflection_lm,
- max_metric_calls=2,
- enable_tool_optimization=True,
- )
-
- trainset = [dspy.Example(query="test", answer="test").with_inputs("query")]
- return optimizer, trainset
-
-
-def get_predictor_name(program, predictor):
- """Find predictor name by object identity in named_predictors().
-
- Args:
- program: DSPy module
- predictor: Predictor object to find
-
- Returns:
- str: Predictor name (e.g., "pred", "agent.pred")
- """
- for name, pred in program.named_predictors():
- if pred is predictor:
- return name
- raise ValueError(f"Predictor not found: {predictor}")
-
-
-def test_skip_predictor_without_tools(monkeypatch):
- """Skip predictors without Tool annotations."""
- seed_candidate = setup_seed_candidate_capture(monkeypatch)
-
- class PlainSignature(dspy.Signature):
- """Answer questions."""
- query: str = dspy.InputField()
- answer: str = dspy.OutputField()
-
- class PlainAgent(dspy.Module):
- def __init__(self):
- super().__init__()
- self.pred = dspy.Predict(PlainSignature)
-
- def forward(self, query):
- return self.pred(query=query)
-
- program = PlainAgent()
- optimizer, trainset = create_optimizer(
- task_responses=[{"answer": "test"}] * 20, # Repeat for GEPA iterations
- reflection_responses=[{"improved_instruction": "optimized"}] * 20 # Repeat for GEPA iterations
- )
- optimizer.compile(program, trainset=trainset, valset=trainset)
-
- predictor_name = get_predictor_name(program, program.pred)
- assert predictor_name in seed_candidate
-
- # Should be plain string instruction, not JSON config
- instruction = seed_candidate[predictor_name]
- assert isinstance(instruction, str)
-
-
-def test_detect_react_module(monkeypatch):
- """Detect ReAct module with tools."""
- seed_candidate = setup_seed_candidate_capture(monkeypatch)
-
- program = dspy.ReAct("question -> answer", tools=[search])
- optimizer, trainset = create_optimizer(
- task_responses=[
- {"next_thought": "I should search", "next_tool_name": "search", "next_tool_args": {"query": "test"}},
- {"next_thought": "Done", "next_tool_name": "finish", "next_tool_args": {}},
- {"reasoning": "Based on search", "answer": "test"},
- ] * 20, # Repeat for GEPA iterations
- reflection_responses=[
- {
- "improved_predictor_instruction": "optimized react",
- "improved_extract_instruction": "optimized extract",
- "improved_tool_search_desc": "optimized search desc",
- "improved_tool_search_arg_query_desc": "optimized query desc"
- }
- ] * 20 # Repeat for GEPA iterations
- )
- optimizer.compile(program, trainset=trainset, valset=trainset)
-
- # Verify detection - use extract.predict as primary (for tracing)
- extract_name = get_predictor_name(program, program.extract.predict)
- component_key = f"{TOOL_MODULE_PREFIX}:{extract_name}"
- assert component_key in seed_candidate
-
- tool_config = json.loads(seed_candidate[component_key])
- assert "tools" in tool_config
-
-
-def test_detect_multiple_react_modules(monkeypatch):
- """Detect multiple ReAct modules in workflow."""
- seed_candidate = setup_seed_candidate_capture(monkeypatch)
-
- class Workflow(dspy.Module):
- def __init__(self):
- super().__init__()
- self.searcher = dspy.ReAct("query -> results", tools=[search])
- self.analyzer = dspy.ReAct("data -> analysis", tools=[analyze])
-
- def forward(self, query):
- results = self.searcher(query=query)
- return self.analyzer(data=results.results)
-
- program = Workflow()
- optimizer, trainset = create_optimizer(
- task_responses=[
- {"next_thought": "Searching", "next_tool_name": "search", "next_tool_args": {"query": "test"}},
- {"next_thought": "Done", "next_tool_name": "finish", "next_tool_args": {}},
- {"reasoning": "Found results", "results": "data"},
- {"next_thought": "Analyzing", "next_tool_name": "analyze", "next_tool_args": {"data": "test"}},
- {"next_thought": "Done", "next_tool_name": "finish", "next_tool_args": {}},
- {"reasoning": "Analyzed", "analysis": "result"},
- ] * 20, # Repeat for GEPA iterations
- reflection_responses=[
- {
- "improved_predictor_instruction": "opt react search",
- "improved_extract_instruction": "opt extract search",
- "improved_tool_search_desc": "opt search desc",
- "improved_tool_search_arg_query_desc": "opt query desc"
- },
- {
- "improved_predictor_instruction": "opt react analyze",
- "improved_extract_instruction": "opt extract analyze",
- "improved_tool_analyze_desc": "opt analyze desc",
- "improved_tool_analyze_arg_data_desc": "opt data desc"
- }
- ] * 20 # Repeat for GEPA iterations
- )
- optimizer.compile(program, trainset=trainset, valset=trainset)
-
- # Verify both detected - use extract.predict as primary (for tracing)
- searcher_name = get_predictor_name(program, program.searcher.extract.predict)
- analyzer_name = get_predictor_name(program, program.analyzer.extract.predict)
-
- searcher_key = f"{TOOL_MODULE_PREFIX}:{searcher_name}"
- analyzer_key = f"{TOOL_MODULE_PREFIX}:{analyzer_name}"
-
- assert searcher_key in seed_candidate
- assert analyzer_key in seed_candidate
-
-
-def test_apply_optimized_react_descriptions():
- """Apply optimized tool descriptions to ReAct modules."""
-
- program = dspy.ReAct("question -> answer", tools=[search])
-
- # Create mock optimized candidate - use extract.predict as primary (for tracing)
- react_name = get_predictor_name(program, program.react)
- extract_predict_name = get_predictor_name(program, program.extract.predict)
-
- component_key = f"{TOOL_MODULE_PREFIX}:{extract_predict_name}"
-
- optimized_candidate = {
- component_key: json.dumps({
- react_name: "OPTIMIZED: React instruction",
- extract_predict_name: "OPTIMIZED: Extract instruction",
- "tools": {
- "search": {
- "desc": "OPTIMIZED: Search tool",
- "args": {"query": {"type": "string"}},
- }
- }
- })
- }
-
- # Apply optimizations
- adapter = DspyAdapter(
- student_module=program,
- metric_fn=lambda example, pred, trace=None: 0.5,
- feedback_map={},
- enable_tool_optimization=True,
- )
- rebuilt = adapter.build_program(optimized_candidate)
-
- # Verify instructions updated
- assert rebuilt.react.signature.instructions == "OPTIMIZED: React instruction"
- assert rebuilt.extract.predict.signature.instructions == "OPTIMIZED: Extract instruction"
-
- # Verify tool updated
- assert rebuilt.tools["search"].desc == "OPTIMIZED: Search tool"
-
-
-def test_detect_nested_react_modules(monkeypatch):
- """Detect ReAct modules in nested program structure."""
- seed_candidate = setup_seed_candidate_capture(monkeypatch)
-
- class Worker(dspy.Module):
- def __init__(self):
- super().__init__()
- self.react = dspy.ReAct("task -> result", tools=[analyze])
-
- def forward(self, task):
- return self.react(task=task)
-
- class Orchestrator(dspy.Module):
- def __init__(self):
- super().__init__()
- self.searcher = dspy.ReAct("query -> results", tools=[search])
- self.worker = Worker()
-
- def forward(self, query):
- results = self.searcher(query=query)
- return self.worker(task=results.results)
-
- program = Orchestrator()
- optimizer, trainset = create_optimizer(
- task_responses=[
- {"next_thought": "Search", "next_tool_name": "search", "next_tool_args": {"query": "test"}},
- {"next_thought": "Done", "next_tool_name": "finish", "next_tool_args": {}},
- {"reasoning": "Found", "results": "data"},
- {"next_thought": "Analyze", "next_tool_name": "analyze", "next_tool_args": {"data": "test"}},
- {"next_thought": "Done", "next_tool_name": "finish", "next_tool_args": {}},
- {"reasoning": "Analyzed", "result": "final"},
- ] * 20, # Repeat for GEPA iterations
- reflection_responses=[
- {
- "improved_predictor_instruction": "opt react search",
- "improved_extract_instruction": "opt extract search",
- "improved_tool_search_desc": "opt search desc",
- "improved_tool_search_arg_query_desc": "opt query desc"
- },
- {
- "improved_predictor_instruction": "opt react analyze",
- "improved_extract_instruction": "opt extract analyze",
- "improved_tool_analyze_desc": "opt analyze desc",
- "improved_tool_analyze_arg_data_desc": "opt data desc"
- }
- ] * 20 # Repeat for GEPA iterations
- )
- optimizer.compile(program, trainset=trainset, valset=trainset)
-
- # Verify nested modules detected with full paths - use extract.predict as primary (for tracing)
- searcher_name = get_predictor_name(program, program.searcher.extract.predict)
- worker_extract_name = get_predictor_name(program, program.worker.react.extract.predict)
-
- searcher_key = f"{TOOL_MODULE_PREFIX}:{searcher_name}"
- worker_key = f"{TOOL_MODULE_PREFIX}:{worker_extract_name}"
-
- assert searcher_key in seed_candidate
- assert worker_key in seed_candidate
-
- # Verify full paths preserved (not truncated)
- assert "searcher" in searcher_name # Contains parent path
- assert "worker" in worker_extract_name # Contains nested path
-
-
-def test_selective_optimization_with_none_returns():
- """Verify selective optimization when reflection LM returns None for some fields."""
-
- program = dspy.ReAct("question -> answer", tools=[search, calculate])
-
- react_name = get_predictor_name(program, program.react)
- extract_name = get_predictor_name(program, program.extract.predict)
- component_key = f"{TOOL_MODULE_PREFIX}:{extract_name}"
-
- # Mock selective optimization (only react instruction and search tool updated)
- optimized_candidate = {
- component_key: json.dumps({
- react_name: "OPTIMIZED: React instruction",
- extract_name: program.extract.predict.signature.instructions,
- "tools": {
- "search": {
- "desc": "OPTIMIZED: Search tool",
- "args": {"query": {"type": "string"}},
- }
- }
- })
- }
-
- adapter = DspyAdapter(
- student_module=program,
- metric_fn=lambda example, pred, trace=None: 0.5,
- feedback_map={},
- enable_tool_optimization=True,
- )
- rebuilt = adapter.build_program(optimized_candidate)
-
- # Verify selective updates
- assert rebuilt.react.signature.instructions == "OPTIMIZED: React instruction"
- assert rebuilt.extract.predict.signature.instructions == program.extract.predict.signature.instructions
- assert rebuilt.tools["search"].desc == "OPTIMIZED: Search tool"
-
- # Original unchanged (calculate not in optimized candidate)
- assert rebuilt.tools["calculate"].desc == program.tools["calculate"].desc