"""optimize_anything "omni" + Claude Code. Implements the two-phase **omni-GEPA** pattern from GEPA's release blog (https://gepa-ai.github.io/gepa/blog/2026/07/22/optimize-anything-omni/) on the "pelican riding a bicycle" SVG task, driven entirely by the local `claude` CLI (Claude Code) — no hosted VLM, no API keys: * PHASE 1 (explore) — ``optimize_best_of`` runs *three* engines in parallel and keeps the single best candidate: - ``gepa`` : reflective evolution; its reflection LM is the `claude` CLI (it *sees* each rendered SVG). - ``autoresearch`` : a black-box research optimizer that spawns ``claude --print`` to iterate on the artifact. - ``meta_harness`` : an iterative meta-optimizer, also Claude-driven. * PHASE 2 (continue) — a fresh ``gepa`` run is *seeded from the winner*. This continuation-from-the-best is what the blog calls omni-GEPA. SCORING for every engine goes through one evaluator: render the SVG to PNG, show it to Claude Code, and parse ``SCORE: X/10``. The score + textual feedback (Actionable Side Information) is returned to whichever engine asked for it. Prereqs: * `claude` CLI on PATH and authenticated (`claude -p "hi"` works). The agentic engines shell out to `claude --print` themselves. * `bwrap` on PATH if GEPA_SANDBOX=1 (the default) — the agentic engines jail their `claude` subprocess, allowing only localhost (the eval server) and api.anthropic.com. Set GEPA_SANDBOX=0 to run unsandboxed. * `cairosvg` for SVG -> PNG rendering. * gepa installed from git main (the "omni" API is unreleased as of 0.1.4); see pyproject.toml. Run: uv run python optanything_claudecode.py """ import base64 import os import re import subprocess import tempfile import cairosvg from gepa.optimize_anything import ( optimize_anything, optimize_best_of, OptimizeAnythingConfig, ) from gepa.gepa_launcher import GEPAConfig, EngineConfig, ReflectionConfig from gepa import Image GOAL = "a pelican riding a bicycle" # Per-engine eval-server budget. Phase 1 spends this on EACH of the three # engines (they run concurrently), phase 2 spends it once more on gepa. MAX_EVALS = int(os.environ.get("GEPA_MAX_EVALS", "20")) # Model the agentic engines pass to `claude --model`. An alias ("sonnet", # "opus", "haiku") or a full id both work. CLAUDE_MODEL = os.environ.get("GEPA_CLAUDE_MODEL", "sonnet") CLAUDE_TIMEOUT = int(os.environ.get("GEPA_CLAUDE_TIMEOUT", "600")) # The agentic engines jail their `claude` subprocess with bwrap by default. SANDBOX = os.environ.get("GEPA_SANDBOX", "1") not in ("0", "false", "no", "") # --------------------------------------------------------------------------- # SVG rendering + Claude-Code scoring. # --------------------------------------------------------------------------- _SVG_RE = re.compile(r"", re.IGNORECASE | re.DOTALL) def coerce_svg(candidate: str) -> str: """Extract SVG source from a candidate string. The `gepa` engine hands us clean SVG, but the agentic engines return whatever `claude` wrote — often wrapped in ```svg fences or prefaced with prose. Pull out the first ``...`` block; fall back to the raw text so a render error (and its feedback) still flows back to the engine. """ m = _SVG_RE.search(candidate) return m.group(0) if m else candidate.strip() def render_image(svg_code: str) -> str: """Render SVG source to a base64-encoded PNG string.""" png_bytes = cairosvg.svg2png(bytestring=svg_code.encode("utf-8")) return base64.b64encode(png_bytes).decode("utf-8") def score_with_claude(image_b64: str, criteria: str) -> tuple[float, str]: """Show the rendered image to Claude Code and parse `SCORE: X/10` -> (0..1, text).""" tmpdir = tempfile.mkdtemp(prefix="gepa_score_") path = os.path.join(tmpdir, "candidate.png") with open(path, "wb") as f: f.write(base64.b64decode(image_b64)) prompt = ( f"{criteria}\n\n" f"Open and look at the image, then give one or two sentences of concrete, " f"actionable feedback on what to improve. End your reply with a line " f"exactly of the form 'SCORE: X/10'.\n\nImage: @{path}" ) text = _claude_cli(prompt) m = re.search(r"SCORE:\s*([0-9]+(?:\.[0-9]+)?)\s*/\s*10", text, re.IGNORECASE) score = (float(m.group(1)) / 10.0) if m else 0.0 return max(0.0, min(1.0, score)), text # --------------------------------------------------------------------------- # Claude Code CLI as the reflection LM for the `gepa` engine. # --------------------------------------------------------------------------- def _claude_cli(prompt: str) -> str: result = subprocess.run( ["claude", "-p", prompt], capture_output=True, text=True, timeout=CLAUDE_TIMEOUT, ) if result.returncode != 0: raise RuntimeError(f"claude -p failed (code {result.returncode}): {result.stderr}") return result.stdout def _data_uri_to_file(url: str, tmpdir: str, idx: int) -> str | None: """Decode a `data:image/...;base64,...` URI to a temp file; return its path.""" if not url.startswith("data:"): return None header, _, b64 = url.partition(",") ext = ".jpg" if "image/jpeg" in header else ".webp" if "image/webp" in header else ".png" path = os.path.join(tmpdir, f"reflect_img_{idx}{ext}") with open(path, "wb") as f: f.write(base64.b64decode(b64)) return path def claude_reflection_lm(prompt): """Reflection LM backed by the `claude` CLI. GEPA passes either a plain string (text-only reflective data) or an OpenAI-style chat-messages list when images are present (our RenderedSVG). We flatten to text and, for any inline image, write it to a temp PNG and @-reference it so Claude Code can view it. """ if isinstance(prompt, str): return _claude_cli(prompt) text_parts: list[str] = [] img_paths: list[str] = [] tmpdir = tempfile.mkdtemp(prefix="gepa_claude_") for msg in prompt: content = msg.get("content", "") if isinstance(content, str): text_parts.append(content) continue for part in content: if part.get("type") == "text": text_parts.append(part.get("text", "")) elif part.get("type") == "image_url": path = _data_uri_to_file( part["image_url"]["url"], tmpdir, len(img_paths) + 1 ) if path: img_paths.append(path) prompt_text = "\n\n".join(p for p in text_parts if p) if img_paths: refs = " ".join(f"@{p}" for p in img_paths) prompt_text += ( "\n\nThe referenced image(s) are the rendered SVG(s) above — " f"open and inspect them: {refs}" ) return _claude_cli(prompt_text) # --------------------------------------------------------------------------- # Task definition — ONE evaluator, shared by every engine. # # In the omni layer the candidate is a plain SVG *string* (only the `gepa` # engine accepts a multi-component dict seed; autoresearch/meta_harness require # a single text). So `evaluate` takes the SVG string directly. # --------------------------------------------------------------------------- def evaluate(candidate, example): """Render SVG -> image, score with Claude Code, return (score, side_info).""" svg = coerce_svg(candidate) try: image = render_image(svg) except Exception as e: # Give the engine actionable feedback instead of crashing the run. return 0.0, {"Feedback": f"SVG failed to render ({type(e).__name__}): {e}"} score, feedback = score_with_claude(image, example["criteria"]) return score, { "RenderedSVG": Image(base64_data=image, media_type="image/png"), "Feedback": feedback, } VISUAL_ASPECTS = [ # 6 visual aspects -> Pareto-efficient selection (gepa engine). {"id": "overall", "criteria": f"Rate overall quality of this SVG ({GOAL}). SCORE: X/10"}, {"id": "anatomy", "criteria": "Rate pelican accuracy: beak, pouch, plumage. SCORE: X/10"}, {"id": "bicycle", "criteria": "Rate bicycle: wheels, frame, handlebars, pedals. SCORE: X/10"}, {"id": "composition", "criteria": "Rate how convincingly the pelican rides the bicycle. SCORE: X/10"}, {"id": "visual", "criteria": "Rate visual appeal, scenery, and color usage. SCORE: X/10"}, {"id": "craft", "criteria": "Rate SVG technical quality: shapes, layering. SCORE: X/10"}, ] OBJECTIVE = f"Optimize SVG code to illustrate '{GOAL}'. Output ONLY valid SVG." BACKGROUND = ( "The candidate is raw SVG source. It is rendered to a PNG and graded 0-10 " "by a vision model against several visual criteria (pelican anatomy, the " "bicycle, the riding composition, appeal, and SVG craft). Higher is better. " "Output ONLY a single valid ... document." ) def _gepa_config() -> OptimizeAnythingConfig: """The reflective-evolution engine, with Claude Code as its reflection LM. ``engine_config`` is forwarded verbatim as ``GEPAConfig(**engine_config)`` by the omni gepa engine, so we build real GEPAConfig sub-objects here. """ return OptimizeAnythingConfig( engine="gepa", max_evals=MAX_EVALS, sandbox=SANDBOX, engine_config=dict( engine=EngineConfig(display_progress_bar=True), reflection=ReflectionConfig(reflection_lm=claude_reflection_lm), ), ) def _agentic_config(engine: str) -> OptimizeAnythingConfig: """autoresearch / meta_harness — both spawn `claude --print` themselves.""" return OptimizeAnythingConfig( engine=engine, max_evals=MAX_EVALS, sandbox=SANDBOX, engine_config=dict(model=CLAUDE_MODEL), ) if __name__ == "__main__": seed_svg = open("seed.svg").read() # a plain white canvas task = dict( evaluator=evaluate, dataset=VISUAL_ASPECTS, objective=OBJECTIVE, background=BACKGROUND, ) # -- Phase 1 (explore): run all three engines in parallel, keep the best. -- # NOTE: temporarily running ONLY the autoresearch engine — the gepa and # meta_harness engines are commented out below. print(f"\n=== Phase 1: explore (autoresearch only, " f"max_evals={MAX_EVALS}, sandbox={SANDBOX}) ===") explore = optimize_best_of( seed_svg, configs=[ # _gepa_config(), _agentic_config("autoresearch"), # _agentic_config("meta_harness"), ], max_workers=3, **task, ) print(f"\nPhase 1 best score: {explore.best_score:.3f} " f"({explore.total_evals} evals)") # -- Phase 2 (continue): seed a fresh autoresearch run from the winner. -- print(f"\n=== Phase 2: continue with autoresearch, seeded from the phase-1 " f"winner (max_evals={MAX_EVALS}) ===") omni = optimize_anything( explore.best_candidate, config=_agentic_config("autoresearch"), **task, ) best = omni if omni.best_score >= explore.best_score else explore print(f"\n=== Done. best score: {best.best_score:.3f} ===") print(coerce_svg(best.best_candidate))