← back to invincible-jha__aumai-metaagent

Function bodies 20 total

All specs Real LLM only Function bodies
main function · python · L12-L14 (3 LOC)
examples/quickstart.py
def main() -> None:
    """Entry point for the quickstart example."""
    print("aumai-metaagent quickstart — replace this with real usage.")
evolve_command function · python · L41-L90 (50 LOC)
src/aumai_metaagent/cli.py
def evolve_command(
    generations: int,
    population: int,
    tournament_size: int,
    mutation_rate: float,
    crossover_rate: float,
    elite_fraction: float,
    seed: int | None,
    output_path: Path,
    history_output: Path | None,
) -> None:
    """Run the evolutionary meta-learning loop.

    Example:

        aumai-metaagent evolve --generations 100 --population 30 --seed 42
    """
    config = EvolutionConfig(
        population_size=population,
        generations=generations,
        tournament_size=tournament_size,
        mutation_rate=mutation_rate,
        crossover_rate=crossover_rate,
        elite_fraction=elite_fraction,
        seed=seed,
    )

    click.echo(
        f"Evolving {population} agents for {generations} generation(s) "
        f"(seed={seed}, tournament_size={tournament_size})"
    )

    engine = EvolutionEngine(config)
    best = engine.evolve()

    click.echo(f"\nBest blueprint: {best.blueprint_id}")
    click.echo(f"  Fitness       : {b
generate_command function · python · L103-L121 (19 LOC)
src/aumai_metaagent/cli.py
def generate_command(count: int, seed: int | None, output_path: Path | None) -> None:
    """Generate random agent blueprints.

    Example:

        aumai-metaagent generate --count 5 --seed 0
    """
    import random as _random
    rng = _random.Random(seed)
    generator = BlueprintGenerator(rng=rng)
    blueprints = [generator.random(generation=0) for _ in range(count)]

    output = json.dumps([bp.model_dump() for bp in blueprints], indent=2)

    if output_path:
        output_path.write_text(output, encoding="utf-8")
        click.echo(f"Generated {count} blueprint(s) -> {output_path}")
    else:
        click.echo(output)
BlueprintGenerator class · python · L28-L190 (163 LOC)
src/aumai_metaagent/core.py
class BlueprintGenerator:
    """Generate, mutate, and combine AgentBlueprint objects.

    All randomness is seeded via the provided random.Random instance
    to ensure reproducibility.

    Example:
        >>> rng = random.Random(42)
        >>> gen = BlueprintGenerator(rng)
        >>> blueprint = gen.random(generation=0)
        >>> mutated = gen.mutate(blueprint, mutation_rate=0.3)
        >>> child = gen.crossover(blueprint, mutated)
    """

    _LAYER_SIZES = [16, 32, 64, 128, 256, 512]
    _MIN_LAYERS = 1
    _MAX_LAYERS = 4

    def __init__(self, rng: Optional[random.Random] = None) -> None:
        """Initialise with an optional seeded RNG.

        Args:
            rng: A random.Random instance. Creates a new one if None.
        """
        self._rng = rng or random.Random()

    def random(self, generation: int = 0) -> AgentBlueprint:
        """Generate a fully random AgentBlueprint.

        Args:
            generation: Generation number to stamp on the blueprint.
__init__ method · python · L46-L52 (7 LOC)
src/aumai_metaagent/core.py
    def __init__(self, rng: Optional[random.Random] = None) -> None:
        """Initialise with an optional seeded RNG.

        Args:
            rng: A random.Random instance. Creates a new one if None.
        """
        self._rng = rng or random.Random()
random method · python · L54-L76 (23 LOC)
src/aumai_metaagent/core.py
    def random(self, generation: int = 0) -> AgentBlueprint:
        """Generate a fully random AgentBlueprint.

        Args:
            generation: Generation number to stamp on the blueprint.

        Returns:
            A randomly parameterised AgentBlueprint.
        """
        num_layers = self._rng.randint(self._MIN_LAYERS, self._MAX_LAYERS)
        hidden_layers = [self._rng.choice(self._LAYER_SIZES) for _ in range(num_layers)]

        return AgentBlueprint(
            blueprint_id=self._new_id(),
            hidden_layers=hidden_layers,
            activation=self._rng.choice(list(ActivationFn)),
            optimizer=self._rng.choice(list(OptimizerType)),
            learning_rate=10 ** self._rng.uniform(-5, -1),
            dropout_rate=round(self._rng.uniform(0.0, 0.5), 2),
            memory_size=self._rng.choice([256, 512, 1000, 2000, 5000]),
            exploration_rate=round(self._rng.uniform(0.01, 0.5), 3),
            generation=generation,
        )
mutate method · python · L78-L146 (69 LOC)
src/aumai_metaagent/core.py
    def mutate(self, blueprint: AgentBlueprint, mutation_rate: float = 0.2) -> AgentBlueprint:
        """Return a mutated copy of *blueprint*.

        Each hyperparameter is independently mutated with probability
        *mutation_rate*.  The original blueprint is not modified.

        Args:
            blueprint: The AgentBlueprint to mutate.
            mutation_rate: Probability of mutating each parameter.

        Returns:
            A new mutated AgentBlueprint.
        """
        layers = list(blueprint.hidden_layers)

        if self._rng.random() < mutation_rate:
            # Mutate architecture: add, remove, or resize a layer
            operation = self._rng.choice(["resize", "add", "remove"])
            if operation == "add" and len(layers) < self._MAX_LAYERS:
                layers.append(self._rng.choice(self._LAYER_SIZES))
            elif operation == "remove" and len(layers) > self._MIN_LAYERS:
                layers.pop(self._rng.randrange(len(layers)))
        
Provenance: Repobility (https://repobility.com) — every score reproducible from /scan/
crossover method · python · L148-L187 (40 LOC)
src/aumai_metaagent/core.py
    def crossover(self, parent_a: AgentBlueprint, parent_b: AgentBlueprint) -> AgentBlueprint:
        """Create a child blueprint by crossing over two parents.

        Uses uniform crossover: each hyperparameter is independently
        drawn from either parent with 50% probability.

        Args:
            parent_a: First parent blueprint.
            parent_b: Second parent blueprint.

        Returns:
            A new child AgentBlueprint.
        """
        pick = self._rng.random

        # Crossover hidden layers: take longer or shorter randomly
        layers_a, layers_b = parent_a.hidden_layers, parent_b.hidden_layers
        min_len = min(len(layers_a), len(layers_b))
        max_len = max(len(layers_a), len(layers_b))
        target_len = self._rng.randint(min_len, max_len)
        longer = layers_a if len(layers_a) >= len(layers_b) else layers_b
        shorter = layers_a if len(layers_a) < len(layers_b) else layers_b
        # Pair up existing layers, draw remaining f
EvolutionEngine class · python · L198-L345 (148 LOC)
src/aumai_metaagent/core.py
class EvolutionEngine:
    """Run the evolutionary meta-learning loop.

    Uses tournament selection, elitism, and configurable crossover/mutation.
    The fitness function is injected at construction time — by default a simple
    synthetic function is used for demonstration.

    Example:
        >>> config = EvolutionConfig(population_size=10, generations=5, seed=42)
        >>> engine = EvolutionEngine(config)
        >>> best = engine.evolve()
        >>> print(best.blueprint_id, best.fitness)
    """

    def __init__(
        self,
        config: EvolutionConfig,
        fitness_fn: Optional[Callable[[AgentBlueprint], float]] = None,
    ) -> None:
        """Initialise the engine.

        Args:
            config: Evolution hyperparameters.
            fitness_fn: Optional custom fitness function. If None, uses a
                        synthetic proxy based on architecture shape.
        """
        self._config = config
        self._rng = random.Random(config.seed)
      
__init__ method · python · L212-L228 (17 LOC)
src/aumai_metaagent/core.py
    def __init__(
        self,
        config: EvolutionConfig,
        fitness_fn: Optional[Callable[[AgentBlueprint], float]] = None,
    ) -> None:
        """Initialise the engine.

        Args:
            config: Evolution hyperparameters.
            fitness_fn: Optional custom fitness function. If None, uses a
                        synthetic proxy based on architecture shape.
        """
        self._config = config
        self._rng = random.Random(config.seed)
        self._generator = BlueprintGenerator(rng=self._rng)
        self._fitness_fn = fitness_fn or self._default_fitness
        self._history: list[PerformanceMetric] = []
evolve method · python · L230-L290 (61 LOC)
src/aumai_metaagent/core.py
    def evolve(self) -> PerformanceMetric:
        """Run the full evolution loop and return the best metric found.

        Returns:
            PerformanceMetric of the best blueprint found across all generations.
        """
        cfg = self._config
        population = [
            self._generator.random(generation=0) for _ in range(cfg.population_size)
        ]

        all_time_best: Optional[PerformanceMetric] = None

        for generation in range(cfg.generations):
            # Evaluate
            metrics: list[PerformanceMetric] = []
            for bp in population:
                fitness = self._fitness_fn(bp)
                metric = PerformanceMetric(
                    blueprint_id=bp.blueprint_id,
                    fitness=fitness,
                    episode_reward=fitness * 100,
                    success_rate=min(1.0, fitness),
                    generation=generation,
                )
                metrics.append(metric)
                self._history.
get_history method · python · L292-L294 (3 LOC)
src/aumai_metaagent/core.py
    def get_history(self) -> list[PerformanceMetric]:
        """Return all PerformanceMetric records from the evolution run."""
        return list(self._history)
_tournament_select method · python · L300-L316 (17 LOC)
src/aumai_metaagent/core.py
    def _tournament_select(
        self, population: list[AgentBlueprint], metrics: list[PerformanceMetric]
    ) -> AgentBlueprint:
        """Select one individual via tournament selection.

        Args:
            population: Current generation blueprints.
            metrics: Corresponding performance metrics.

        Returns:
            Winner of the tournament.
        """
        fitness_map = {m.blueprint_id: m.fitness for m in metrics}
        k = min(self._config.tournament_size, len(population))
        contestants = self._rng.sample(population, k)
        winner = max(contestants, key=lambda bp: fitness_map.get(bp.blueprint_id, 0.0))
        return winner
_default_fitness method · python · L319-L345 (27 LOC)
src/aumai_metaagent/core.py
    def _default_fitness(blueprint: AgentBlueprint) -> float:
        """Synthetic fitness proxy for demonstration.

        Rewards moderate-depth networks with tanh activation and Adam.
        Real-world use should inject a proper fitness function.

        Args:
            blueprint: Blueprint to evaluate.

        Returns:
            Fitness scalar in roughly [0, 1].
        """
        depth_score = 1.0 / (1.0 + abs(len(blueprint.hidden_layers) - 2))
        lr_score = 1.0 - abs(blueprint.learning_rate - 1e-3) / 1e-3
        lr_score = max(0.0, min(1.0, lr_score))
        activation_bonus = 0.1 if blueprint.activation == ActivationFn.TANH else 0.0
        optimizer_bonus = 0.05 if blueprint.optimizer == OptimizerType.ADAM else 0.0
        dropout_penalty = blueprint.dropout_rate * 0.2

        fitness = (
            depth_score * 0.4
            + lr_score * 0.3
            + activation_bonus
            + optimizer_bonus
            - dropout_penalty
        )
        return 
ActivationFn class · python · L11-L18 (8 LOC)
src/aumai_metaagent/models.py
class ActivationFn(str, Enum):
    """Supported activation functions for neural network layers."""

    RELU = "relu"
    TANH = "tanh"
    SIGMOID = "sigmoid"
    LINEAR = "linear"
    GELU = "gelu"
Source: Repobility analyzer · https://repobility.com
OptimizerType class · python · L21-L27 (7 LOC)
src/aumai_metaagent/models.py
class OptimizerType(str, Enum):
    """Supported optimizers."""

    ADAM = "adam"
    SGD = "sgd"
    RMSPROP = "rmsprop"
    ADAMW = "adamw"
AgentBlueprint class · python · L30-L68 (39 LOC)
src/aumai_metaagent/models.py
class AgentBlueprint(BaseModel):
    """A parameterised description of an agent architecture.

    Attributes:
        blueprint_id: Unique identifier.
        hidden_layers: List of hidden layer sizes.
        activation: Activation function for hidden layers.
        optimizer: Optimizer type.
        learning_rate: Learning rate for the optimizer.
        dropout_rate: Dropout rate for regularisation.
        memory_size: Replay buffer / context window size.
        exploration_rate: Epsilon for epsilon-greedy exploration.
        generation: Evolution generation in which this was created.
        parent_ids: Blueprint IDs of parent(s) used to create this.
        extra_params: Extensible additional hyperparameters.
    """

    blueprint_id: str
    hidden_layers: list[int] = Field(default_factory=lambda: [64, 64])
    activation: ActivationFn = ActivationFn.RELU
    optimizer: OptimizerType = OptimizerType.ADAM
    learning_rate: float = Field(default=1e-3, gt=0.0)
    dropout_rat
parameter_count method · python · L59-L68 (10 LOC)
src/aumai_metaagent/models.py
    def parameter_count(self) -> int:
        """Estimate total trainable parameter count from hidden_layers."""
        if not self.hidden_layers:
            return 0
        total = 0
        prev = self.hidden_layers[0]
        for size in self.hidden_layers[1:]:
            total += prev * size + size
            prev = size
        return total
PerformanceMetric class · python · L71-L90 (20 LOC)
src/aumai_metaagent/models.py
class PerformanceMetric(BaseModel):
    """A measured performance outcome for an AgentBlueprint.

    Attributes:
        blueprint_id: Blueprint this metric belongs to.
        fitness: Primary fitness score (higher is better).
        episode_reward: Mean reward over evaluation episodes.
        success_rate: Fraction of tasks completed successfully.
        evaluation_steps: Number of environment steps used for evaluation.
        generation: Generation at which this was measured.
        notes: Optional contextual notes.
    """

    blueprint_id: str
    fitness: float = Field(default=0.0)
    episode_reward: float = Field(default=0.0)
    success_rate: float = Field(default=0.0, ge=0.0, le=1.0)
    evaluation_steps: int = Field(default=0, ge=0)
    generation: int = Field(default=0, ge=0)
    notes: Optional[str] = None
EvolutionConfig class · python · L93-L114 (22 LOC)
src/aumai_metaagent/models.py
class EvolutionConfig(BaseModel):
    """Hyperparameters for the evolutionary meta-learning loop.

    Attributes:
        population_size: Number of blueprints per generation.
        generations: Total number of evolution generations.
        tournament_size: Number of individuals in each tournament selection.
        mutation_rate: Probability of mutating each hyperparameter.
        crossover_rate: Probability of crossover vs. cloning.
        elite_fraction: Fraction of top individuals carried to next generation.
        seed: Optional random seed.
        evaluation_episodes: Episodes per fitness evaluation.
    """

    population_size: int = Field(default=20, gt=0)
    generations: int = Field(default=10, gt=0)
    tournament_size: int = Field(default=4, gt=0)
    mutation_rate: float = Field(default=0.2, ge=0.0, le=1.0)
    crossover_rate: float = Field(default=0.7, ge=0.0, le=1.0)
    elite_fraction: float = Field(default=0.1, ge=0.0, le=1.0)
    seed: Optional[int] = None