Suhasdev's picture
Deploy Universal Prompt Optimizer to HF Spaces (clean)
cacd4d0
"""
Base Genetic Operator Interface.
Defines the abstract interface for all genetic operators following
the Interface Segregation Principle (ISP) of SOLID.
"""
from abc import ABC, abstractmethod
from typing import List, Callable
import logging
logger = logging.getLogger(__name__)
class BaseGeneticOperator(ABC):
"""
Abstract base class for genetic operators.
All genetic operators (crossover, mutation, etc.) should inherit from this
class and implement the __call__ method.
Design Principles:
- Single Responsibility: Each operator does one thing
- Open/Closed: Extend via inheritance, don't modify
- Liskov Substitution: Any operator works where base is expected
- Interface Segregation: Minimal required interface
- Dependency Inversion: Depend on abstractions (LLM callable)
"""
@abstractmethod
def __call__(self, *args, **kwargs) -> str:
"""
Execute the genetic operation.
Returns:
str: New prompt generated by the operation
"""
pass
@abstractmethod
def _build_prompt(self, *args, **kwargs) -> str:
"""
Build the LLM prompt for this operation.
Returns:
str: Prompt to send to the LLM
"""
pass
class BaseCrossoverOperator(BaseGeneticOperator):
"""
Abstract base class for crossover operators.
Crossover combines multiple parent prompts to create offspring
that inherit good traits from both parents.
"""
@abstractmethod
def __call__(
self,
parents: List, # List[PromptCandidate]
target_fitness: float,
llm: Callable[[str], str]
) -> str:
"""
Combine parent prompts to create offspring.
Args:
parents: List of parent PromptCandidate objects
target_fitness: Desired fitness for offspring
llm: Language model callable
Returns:
str: Offspring prompt
"""
pass
class BaseMutationOperator(BaseGeneticOperator):
"""
Abstract base class for mutation operators.
Mutation creates variations of a parent prompt to explore
new regions of the search space.
"""
@abstractmethod
def __call__(
self,
parent, # PromptCandidate
population: List, # List[PromptCandidate]
llm: Callable[[str], str]
) -> str:
"""
Mutate a parent prompt to create a variation.
Args:
parent: Parent PromptCandidate to mutate
population: Current population for diversity guidance
llm: Language model callable
Returns:
str: Mutated prompt
"""
pass