File size: 11,385 Bytes
b381f1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""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"<svg\b.*?</svg>", 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 ``<svg>...</svg>`` 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 <svg>...</svg> 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))