dspy.GEPA: 반성적 프롬프트 옵티마이저

dspy.GEPA: 반성적 프롬프트 옵티마이저

GEPA(Genetic-Pareto)는 논문 “GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning”(Agrawal et al., 2025)에서 제안한 반성적(reflective) 옵티마이저로, 임의 시스템의 텍스트 컴포넌트(예: 프롬프트)를 적응적으로 진화시킵니다. metric이 반환하는 스칼라 점수 외에도, 사용자는 GEPA에 텍스트 피드백을 제공해 최적화 과정을 안내할 수 있습니다. 이러한 텍스트 피드백은 GEPA가 시스템이 그 점수를 받은 이유를 더 잘 파악하게 해 주고, GEPA는 점수를 개선할 방법을 식별하기 위해 내부적으로 성찰(introspection)할 수 있습니다. 덕분에 GEPA는 아주 적은 rollout만으로도 고성능 프롬프트를 제안할 수 있습니다.

출처: 문서

본문

dspy.GEPA(
    metric: GEPAFeedbackMetric,
    *,
    auto: Literal['light', 'medium', 'heavy'] | None = None,
    max_full_evals: int | None = None,
    max_metric_calls: int | None = None,
    reflection_minibatch_size: int = 3,
    candidate_selection_strategy: Literal['pareto', 'current_best'] = 'pareto',
    reflection_lm: LM | None = None,
    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',
    use_merge: bool = True,
    max_merge_invocations: int | None = 5,
    num_threads: int | None = None,
    failure_score: float = 0.0,
    perfect_score: float = 1.0,
    log_dir: str | None = None,
    track_stats: bool = False,
    use_wandb: bool = False,
    wandb_api_key: str | None = None,
    wandb_init_kwargs: dict[str, Any] | None = None,
    track_best_outputs: bool = False,
    warn_on_score_mismatch: bool = True,
    use_mlflow: bool = False,
    seed: int | None = 0,
    gepa_kwargs: dict | None = None,
)
  • Bases: Teleprompter

GEPA는 복잡한 시스템의 텍스트 컴포넌트를 진화시키는 데 반성을 사용하는 진화적 옵티마이저입니다. GEPA는 논문 GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning에서 제안되었습니다. GEPA 최적화 엔진은 gepa 패키지(https://github.com/gepa-ai/gepa)가 제공합니다.

GEPA는 DSPy 모듈 실행의 전체 trace를 캡처하고, 특정 predictor에 해당하는 trace 부분을 식별한 뒤, 그 predictor의 행동을 반성해 새 지시문을 제안합니다. GEPA는 사용자가 옵티마이저에 텍스트 피드백을 제공할 수 있게 하며, 이 피드백은 predictor의 진화를 안내하는 데 사용됩니다. 텍스트 피드백은 개별 predictor 단위로도, 전체 시스템 실행 수준으로도 제공할 수 있습니다.

GEPA 옵티마이저에 피드백을 제공하려면 metric을 다음과 같이 구현하세요:

def metric(
    gold: Example,
    pred: Prediction,
    trace: Optional[DSPyTrace] = None,
    pred_name: Optional[str] = None,
    pred_trace: Optional[DSPyTrace] = None,
    program_trace: Optional[DSPyTrace] = None,
) -> float | ScoreWithFeedback:
    """
    This function is called with the following arguments:
    - gold: The gold example.
    - pred: The predicted output.
    - trace: Optional. The trace of the program's execution.
    - pred_name: Optional. The name of the target predictor currently being optimized by GEPA, for which
        the feedback is being requested.
    - pred_trace: Optional. The trace of the target predictor's execution GEPA is seeking feedback for.
    - program_trace: Optional. The program's execution trace, supplied at scoring time when a `dspy.Flex`
        submodule is being optimized. Declare it to score against how the answer was produced (e.g. an
        LM-call penalty). Defaults to None.

    Note the `pred_name` and `pred_trace` arguments. During optimization, GEPA will call the metric to obtain
    feedback for individual predictors being optimized. GEPA provides the name of the predictor in `pred_name`
    and the sub-trace (of the trace) corresponding to the predictor in `pred_trace`.
    If available at the predictor level, the metric should return {'score': float, 'feedback': str} corresponding
    to the predictor.
    If not available at the predictor level, the metric can also return a text feedback at the program level
    (using just the gold, pred and trace).
    If no feedback is returned, GEPA will use a simple text feedback consisting of just the score:
    f"This trajectory got a score of {score}."
    """
    ...

GEPA는 배치 추론 시점 검색(batch inference-time search) 전략으로도 사용할 수 있습니다. valset=trainset, track_stats=True, track_best_outputs=True로 전달하고, compile이 반환하는 최적화 프로그램의 detailed_results 속성으로 배치의 Pareto frontier를 얻습니다. optimized_program.detailed_results.best_outputs_valset에는 배치의 각 작업에 대한 최적 출력이 들어 있습니다.

Examples

gepa = GEPA(metric=metric, track_stats=True)
batch_of_tasks = [dspy.Example(...) for task in tasks]
new_prog = gepa.compile(student, trainset=trainset, valset=batch_of_tasks)
pareto_frontier = new_prog.detailed_results.val_aggregate_scores
# pareto_frontier is a list of scores, one for each task in the batch.

Methods

compile(student, *, trainset, teacher=None, valset=None) -> Module

def compile(
    self,
    student: Module,
    *,
    trainset: list[Example],
    teacher: Module | None = None,
    valset: list[Example] | None = None,
) -> Module:
    """
    GEPA uses the trainset to perform reflective updates to the prompt, but uses the valset for tracking Pareto scores.
    If no valset is provided, GEPA will use the trainset for both.

    Parameters:
    - student: The student module to optimize.
    - trainset: The training set to use for reflective updates.
    - valset: The validation set to use for tracking Pareto scores. If not provided, GEPA will use the trainset for both.
    """
    from gepa import GEPAResult, optimize
    ...

compile은 trainset으로 프롬프트에 대한 반성적 업데이트를 수행하고, valset으로 Pareto 점수를 추적합니다. valset이 없으면 trainset을 둘 다에 사용합니다.

auto_budget(num_preds, num_candidates, valset_size, ...)

auto 모드에 따라 예산(최대 평가 횟수 등)을 자동 산정하기 위한 헬퍼입니다.

GEPA 관련 타입: 이 페이지에는 GEPAFeedbackMetric, DspyGEPAResult(필드: candidates, parents, val_aggregate_scores, val_subscores, per_val_instance_best_candidates, discovery_eval_counts, best_outputs_valset, total_metric_calls, num_full_val_evals, log_dir, seed, best_idx, best_candidate, highest_score_achieved_per_val_task, to_dict() 등) 같은 관련 타입과, dspy.teleprompt.gepa.gepa.DspyGEPAResult, dspy.teleprompt.gepa.gepa.GEPAFeedbackMetric 식별자들이 문서화되어 있습니다. 자세한 내용은 GEPA - Advanced Features 문서를 참고하세요.

더 알아보기 (Learn more)