feat(phase-2.5): mutate_prompt_llm operator + weighted dispatcher + GA wiring
Implementazione completa Phase 2.5 (LLM prompt mutator) seguendo il piano in docs/superpowers/plans/2026-05-11-mutate-prompt-llm-phase-2-5.md. Nuovo modulo src/multi_swarm/genome/mutation_prompt_llm.py: - 6 mutation instructions (tighten_threshold, swap_comparator, add_condition, remove_condition, change_timeframe, add_temporal_gate) - mutate_prompt_llm(g, llm, rng, mutator_tier=ModelTier.B): clona genome con tier B per la call mutator, costruisce system+user prompt con istruzione scelta random, estrae prompt da tag <prompt>...</prompt>, valida - is_valid_prompt(): 3 check (lunghezza >= 50, keyword tecnica, diff > 5% Levenshtein-like via difflib.SequenceMatcher) - Fallback random_mutate su qualsiasi validation fail O LLM exception Esteso src/multi_swarm/genome/mutation.py con weighted_random_mutate dispatcher: con probabilità prompt_mutation_weight invoca mutate_prompt_llm, altrimenti random_mutate. Backward compat: llm=None oppure weight=0 → solo scalare. Integrazione GA loop + RunConfig: - GAConfig.prompt_mutation_weight: float = 0.0 (default off) - next_generation(llm=...) propagato all'invocazione mutator - RunConfig.prompt_mutation_weight con stesso default - run_phase1: passa llm a next_generation solo se weight > 0 - scripts/run_phase1.py: flag CLI --prompt-mutation-weight Tests (+18, 175 totale): - tests/unit/test_mutation_prompt_llm.py (12): extract_prompt, is_valid_prompt 3 check, operator success + fallback su 3 modi (invalid/identical/exception), tier B per LLM call, istruzione scelta dal pool - tests/unit/test_mutation_dispatcher.py (4): weight 0/1/None + distribuzione 30/70 su 1000 estrazioni con tolleranza ±5% - tests/integration/test_ga_loop_with_prompt_mutator.py (2): loop con weight=1.0 produce prompt evoluti; backward compat weight=0 invariato Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -2,10 +2,11 @@ from __future__ import annotations
|
||||
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from ..genome.crossover import uniform_crossover
|
||||
from ..genome.hypothesis import HypothesisAgentGenome
|
||||
from ..genome.mutation import random_mutate
|
||||
from ..genome.mutation import weighted_random_mutate
|
||||
from .selection import elite_select, tournament_select
|
||||
|
||||
|
||||
@@ -15,6 +16,7 @@ class GAConfig:
|
||||
elite_k: int
|
||||
tournament_k: int
|
||||
p_crossover: float
|
||||
prompt_mutation_weight: float = 0.0 # Phase 2.5: opt-in LLM mutator
|
||||
|
||||
|
||||
def next_generation(
|
||||
@@ -22,8 +24,14 @@ def next_generation(
|
||||
fitnesses: dict[str, float],
|
||||
cfg: GAConfig,
|
||||
rng: random.Random,
|
||||
llm: Any | None = None,
|
||||
) -> list[HypothesisAgentGenome]:
|
||||
"""Costruisce la prossima generazione: elitismo + tournament + crossover/mutate."""
|
||||
"""Costruisce la prossima generazione: elitismo + tournament + crossover/mutate.
|
||||
|
||||
Quando ``cfg.prompt_mutation_weight > 0`` e ``llm`` è fornito, la mutazione
|
||||
invoca ``weighted_random_mutate`` che con quella probabilità usa
|
||||
``mutate_prompt_llm`` (Phase 2.5).
|
||||
"""
|
||||
new_pop: list[HypothesisAgentGenome] = list(
|
||||
elite_select(population, fitnesses, cfg.elite_k)
|
||||
)
|
||||
@@ -35,7 +43,9 @@ def next_generation(
|
||||
child = uniform_crossover(p1, p2, rng)
|
||||
else:
|
||||
parent = tournament_select(population, fitnesses, cfg.tournament_k, rng)
|
||||
child = random_mutate(parent, rng)
|
||||
child = weighted_random_mutate(
|
||||
parent, rng, llm=llm, prompt_mutation_weight=cfg.prompt_mutation_weight
|
||||
)
|
||||
new_pop.append(child)
|
||||
|
||||
return new_pop[: cfg.population_size]
|
||||
|
||||
@@ -75,3 +75,23 @@ MUTATION_OPS = (
|
||||
def random_mutate(g: HypothesisAgentGenome, rng: random.Random) -> HypothesisAgentGenome:
|
||||
op = rng.choice(MUTATION_OPS)
|
||||
return op(g, rng)
|
||||
|
||||
|
||||
def weighted_random_mutate(
|
||||
g: HypothesisAgentGenome,
|
||||
rng: random.Random,
|
||||
llm: Any | None = None,
|
||||
prompt_mutation_weight: float = 0.0,
|
||||
) -> HypothesisAgentGenome:
|
||||
"""Dispatcher pesato fra mutate_prompt_llm e random_mutate scalare.
|
||||
|
||||
Con probabilità ``prompt_mutation_weight`` invoca ``mutate_prompt_llm``,
|
||||
altrimenti ``random_mutate``. Se ``llm`` è ``None`` o il peso è 0,
|
||||
è equivalente a ``random_mutate`` (backward-compat).
|
||||
"""
|
||||
if llm is not None and prompt_mutation_weight > 0 and rng.random() < prompt_mutation_weight:
|
||||
# Import inline per evitare ciclo: mutation_prompt_llm importa da mutation.
|
||||
from .mutation_prompt_llm import mutate_prompt_llm
|
||||
|
||||
return mutate_prompt_llm(g, llm, rng)
|
||||
return random_mutate(g, rng)
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Phase 2.5 operator: ``mutate_prompt_llm``.
|
||||
|
||||
Quinto operatore di mutazione che riscrive il ``system_prompt`` di un genoma
|
||||
usando un LLM tier B come "mutator". Genera diversità prompt-level dove gli
|
||||
altri quattro operatori toccano solo i quattro parametri scalari.
|
||||
|
||||
Fallback sicuro: se la mutazione LLM produce output invalido o troppo simile
|
||||
al parent, l'operatore degrada silenziosamente a ``random_mutate``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import re
|
||||
from dataclasses import replace
|
||||
from difflib import SequenceMatcher
|
||||
from typing import Any, Protocol
|
||||
|
||||
from .hypothesis import HypothesisAgentGenome, ModelTier
|
||||
from .mutation import _clone_with, random_mutate
|
||||
|
||||
# Sei tipi di mutazione "atomiche", scelti uniformemente.
|
||||
MUTATION_INSTRUCTIONS: dict[str, str] = {
|
||||
"tighten_threshold": (
|
||||
"Rendi UNA soglia numerica nella strategia più restrittiva del 10-20%. "
|
||||
"Esempio: se RSI > 70 diventa RSI > 78. Lascia tutto il resto identico."
|
||||
),
|
||||
"swap_comparator": (
|
||||
"Inverti UN comparator (gt -> lt, gte -> lte o viceversa) in una sola "
|
||||
"condizione. Mantieni lo stesso intent generale della strategia."
|
||||
),
|
||||
"add_condition": (
|
||||
"Aggiungi UNA condizione AND a una rule esistente per renderla più "
|
||||
"selettiva. La condizione deve usare una feature/indicator coerente con "
|
||||
"il resto della strategia."
|
||||
),
|
||||
"remove_condition": (
|
||||
"Rimuovi UNA condizione ridondante o ovvia da una rule, semplificando la "
|
||||
"logica senza alterarne l'intent principale."
|
||||
),
|
||||
"change_timeframe": (
|
||||
"Modifica UNA finestra rolling/lookback di +/- 20-40% (es. SMA(50) -> "
|
||||
"SMA(70)). Solo un parametro temporale."
|
||||
),
|
||||
"add_temporal_gate": (
|
||||
"Aggiungi UN gate temporale alla strategia usando una delle feature "
|
||||
"'hour', 'dow', 'is_weekend', 'minute_of_hour' per filtrare il "
|
||||
"trading a specifici momenti."
|
||||
),
|
||||
}
|
||||
|
||||
# Keyword tecniche minime per validare che il prompt sia ancora "una strategia".
|
||||
_VALID_KEYWORDS = (
|
||||
"rsi", "sma", "ema", "atr", "momentum", "breakout", "mean", "reversion",
|
||||
"macd", "vwap", "bb", "bollinger", "stoch", "trend", "signal", "buy",
|
||||
"sell", "long", "short", "entry", "exit", "stop", "rule", "condition",
|
||||
"if", "when", "and", "or", "gt", "lt", ">", "<", "ge", "le",
|
||||
"hour", "dow", "weekend", "indicator", "feature",
|
||||
)
|
||||
|
||||
_MIN_PROMPT_LENGTH = 50
|
||||
_MIN_DIFF_RATIO = 0.05 # Levenshtein-like: prompt deve essere almeno 5% diverso
|
||||
|
||||
_MUTATOR_SYSTEM_PROMPT = (
|
||||
"Sei un mutator evolutivo per prompt di strategie di trading algoritmico. "
|
||||
"Ricevi un PROMPT originale e una ISTRUZIONE di mutazione atomica. "
|
||||
"Produci una versione modificata del prompt che applica SOLO quella "
|
||||
"mutazione, preservando intent e struttura generale. "
|
||||
"Output: solo il nuovo prompt fra tag <prompt>...</prompt>. "
|
||||
"Nessun preambolo, nessuna spiegazione."
|
||||
)
|
||||
|
||||
_PROMPT_RE = re.compile(r"<prompt>\s*(.*?)\s*</prompt>", re.DOTALL | re.IGNORECASE)
|
||||
|
||||
|
||||
class _LLMClientLike(Protocol):
|
||||
"""Subset minimo dell'API LLMClient che usa l'operatore.
|
||||
|
||||
Permette di mockare l'LLM nei test senza importare la classe concreta.
|
||||
"""
|
||||
|
||||
def complete(
|
||||
self,
|
||||
genome: HypothesisAgentGenome,
|
||||
system: str,
|
||||
user: str,
|
||||
max_tokens: int = ...,
|
||||
) -> Any: ...
|
||||
|
||||
|
||||
def _extract_prompt(text: str) -> str:
|
||||
"""Estrae il prompt mutato dal completion text.
|
||||
|
||||
Cerca tag ``<prompt>...</prompt>``. Se assenti, ritorna il testo strip.
|
||||
"""
|
||||
m = _PROMPT_RE.search(text)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
return text.strip()
|
||||
|
||||
|
||||
def _string_diff_ratio(a: str, b: str) -> float:
|
||||
"""Ritorna ``1 - similarity`` (0.0 = identici, 1.0 = completamente diversi)."""
|
||||
if not a and not b:
|
||||
return 0.0
|
||||
return 1.0 - SequenceMatcher(None, a, b).ratio()
|
||||
|
||||
|
||||
def is_valid_prompt(new_prompt: str, parent_prompt: str) -> bool:
|
||||
"""Validation gate per il prompt LLM-mutato.
|
||||
|
||||
Tre check:
|
||||
1. Lunghezza minima 50 caratteri.
|
||||
2. Contiene almeno una keyword tecnica (rsi, sma, signal, ecc).
|
||||
3. Diversità Levenshtein-like > 5% rispetto al parent.
|
||||
"""
|
||||
if len(new_prompt) < _MIN_PROMPT_LENGTH:
|
||||
return False
|
||||
lowered = new_prompt.lower()
|
||||
if not any(kw in lowered for kw in _VALID_KEYWORDS):
|
||||
return False
|
||||
if _string_diff_ratio(new_prompt, parent_prompt) < _MIN_DIFF_RATIO:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def mutate_prompt_llm(
|
||||
g: HypothesisAgentGenome,
|
||||
llm: _LLMClientLike,
|
||||
rng: random.Random,
|
||||
mutator_tier: ModelTier = ModelTier.B,
|
||||
max_tokens: int = 2000,
|
||||
) -> HypothesisAgentGenome:
|
||||
"""Operatore di mutazione prompt-level via LLM mutator.
|
||||
|
||||
Sceglie una mutation-instruction casuale fra sei tipi, fa una chiamata
|
||||
LLM tier B per ottenere il prompt mutato, valida l'output. Su validation
|
||||
fail (output troppo corto, non-strategia, troppo simile al parent),
|
||||
fallback silenzioso a ``random_mutate``.
|
||||
"""
|
||||
instruction_key = rng.choice(list(MUTATION_INSTRUCTIONS))
|
||||
instruction = MUTATION_INSTRUCTIONS[instruction_key]
|
||||
|
||||
user_prompt = (
|
||||
f"PROMPT ORIGINALE:\n{g.system_prompt}\n\n"
|
||||
f"ISTRUZIONE DI MUTAZIONE ({instruction_key}):\n{instruction}\n\n"
|
||||
f"Genera la versione modificata fra tag <prompt>...</prompt>."
|
||||
)
|
||||
|
||||
# Mutator usa un tier diverso (B) — clone temporaneo del genoma con tier override.
|
||||
mutator_genome = replace(g, model_tier=mutator_tier)
|
||||
|
||||
try:
|
||||
result = llm.complete(
|
||||
mutator_genome,
|
||||
system=_MUTATOR_SYSTEM_PROMPT,
|
||||
user=user_prompt,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
except Exception:
|
||||
return random_mutate(g, rng)
|
||||
|
||||
new_prompt = _extract_prompt(getattr(result, "text", ""))
|
||||
if not is_valid_prompt(new_prompt, g.system_prompt):
|
||||
return random_mutate(g, rng)
|
||||
|
||||
return _clone_with(g, system_prompt=new_prompt)
|
||||
@@ -49,6 +49,7 @@ class RunConfig:
|
||||
fees_bp: float = 5.0
|
||||
n_trials_dsr: int = 50
|
||||
db_path: Path = field(default_factory=lambda: Path("./runs.db"))
|
||||
prompt_mutation_weight: float = 0.0 # Phase 2.5: opt-in LLM mutator
|
||||
|
||||
|
||||
def run_phase1(
|
||||
@@ -90,6 +91,7 @@ def run_phase1(
|
||||
elite_k=cfg.elite_k,
|
||||
tournament_k=cfg.tournament_k,
|
||||
p_crossover=cfg.p_crossover,
|
||||
prompt_mutation_weight=cfg.prompt_mutation_weight,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -173,7 +175,10 @@ def run_phase1(
|
||||
)
|
||||
|
||||
if gen < cfg.n_generations - 1:
|
||||
population = next_generation(population, fitnesses, ga_cfg, rng)
|
||||
population = next_generation(
|
||||
population, fitnesses, ga_cfg, rng,
|
||||
llm=llm if cfg.prompt_mutation_weight > 0 else None,
|
||||
)
|
||||
|
||||
repo.complete_run(
|
||||
run_id, total_cost=repo.total_cost(run_id), status="completed"
|
||||
|
||||
Reference in New Issue
Block a user