Uploading dataset files from the local data folder.
Browse files- optanything_claudecode.py +276 -0
- optanything_rag_claudecode (1).py +379 -0
- optanything_rag_claudecode.py +378 -0
- semantic-log-file-mcp.tar.gz +3 -0
optanything_claudecode.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""optimize_anything "omni" + Claude Code.
|
| 2 |
+
|
| 3 |
+
Implements the two-phase **omni-GEPA** pattern from GEPA's release blog
|
| 4 |
+
(https://gepa-ai.github.io/gepa/blog/2026/07/22/optimize-anything-omni/) on the
|
| 5 |
+
"pelican riding a bicycle" SVG task, driven entirely by the local `claude` CLI
|
| 6 |
+
(Claude Code) — no hosted VLM, no API keys:
|
| 7 |
+
|
| 8 |
+
* PHASE 1 (explore) — ``optimize_best_of`` runs *three* engines in parallel
|
| 9 |
+
and keeps the single best candidate:
|
| 10 |
+
- ``gepa`` : reflective evolution; its reflection LM is the
|
| 11 |
+
`claude` CLI (it *sees* each rendered SVG).
|
| 12 |
+
- ``autoresearch`` : a black-box research optimizer that spawns
|
| 13 |
+
``claude --print`` to iterate on the artifact.
|
| 14 |
+
- ``meta_harness`` : an iterative meta-optimizer, also Claude-driven.
|
| 15 |
+
* PHASE 2 (continue) — a fresh ``gepa`` run is *seeded from the winner*.
|
| 16 |
+
This continuation-from-the-best is what the blog calls omni-GEPA.
|
| 17 |
+
|
| 18 |
+
SCORING for every engine goes through one evaluator: render the SVG to PNG,
|
| 19 |
+
show it to Claude Code, and parse ``SCORE: X/10``. The score + textual feedback
|
| 20 |
+
(Actionable Side Information) is returned to whichever engine asked for it.
|
| 21 |
+
|
| 22 |
+
Prereqs:
|
| 23 |
+
* `claude` CLI on PATH and authenticated (`claude -p "hi"` works). The
|
| 24 |
+
agentic engines shell out to `claude --print` themselves.
|
| 25 |
+
* `bwrap` on PATH if GEPA_SANDBOX=1 (the default) — the agentic engines jail
|
| 26 |
+
their `claude` subprocess, allowing only localhost (the eval server) and
|
| 27 |
+
api.anthropic.com. Set GEPA_SANDBOX=0 to run unsandboxed.
|
| 28 |
+
* `cairosvg` for SVG -> PNG rendering.
|
| 29 |
+
* gepa installed from git main (the "omni" API is unreleased as of 0.1.4);
|
| 30 |
+
see pyproject.toml.
|
| 31 |
+
|
| 32 |
+
Run: uv run python optanything_claudecode.py
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import base64
|
| 36 |
+
import os
|
| 37 |
+
import re
|
| 38 |
+
import subprocess
|
| 39 |
+
import tempfile
|
| 40 |
+
|
| 41 |
+
import cairosvg
|
| 42 |
+
|
| 43 |
+
from gepa.optimize_anything import (
|
| 44 |
+
optimize_anything,
|
| 45 |
+
optimize_best_of,
|
| 46 |
+
OptimizeAnythingConfig,
|
| 47 |
+
)
|
| 48 |
+
from gepa.gepa_launcher import GEPAConfig, EngineConfig, ReflectionConfig
|
| 49 |
+
from gepa import Image
|
| 50 |
+
|
| 51 |
+
GOAL = "a pelican riding a bicycle"
|
| 52 |
+
|
| 53 |
+
# Per-engine eval-server budget. Phase 1 spends this on EACH of the three
|
| 54 |
+
# engines (they run concurrently), phase 2 spends it once more on gepa.
|
| 55 |
+
MAX_EVALS = int(os.environ.get("GEPA_MAX_EVALS", "20"))
|
| 56 |
+
# Model the agentic engines pass to `claude --model`. An alias ("sonnet",
|
| 57 |
+
# "opus", "haiku") or a full id both work.
|
| 58 |
+
CLAUDE_MODEL = os.environ.get("GEPA_CLAUDE_MODEL", "sonnet")
|
| 59 |
+
CLAUDE_TIMEOUT = int(os.environ.get("GEPA_CLAUDE_TIMEOUT", "600"))
|
| 60 |
+
# The agentic engines jail their `claude` subprocess with bwrap by default.
|
| 61 |
+
SANDBOX = os.environ.get("GEPA_SANDBOX", "1") not in ("0", "false", "no", "")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# ---------------------------------------------------------------------------
|
| 65 |
+
# SVG rendering + Claude-Code scoring.
|
| 66 |
+
# ---------------------------------------------------------------------------
|
| 67 |
+
_SVG_RE = re.compile(r"<svg\b.*?</svg>", re.IGNORECASE | re.DOTALL)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def coerce_svg(candidate: str) -> str:
|
| 71 |
+
"""Extract SVG source from a candidate string.
|
| 72 |
+
|
| 73 |
+
The `gepa` engine hands us clean SVG, but the agentic engines return
|
| 74 |
+
whatever `claude` wrote — often wrapped in ```svg fences or prefaced with
|
| 75 |
+
prose. Pull out the first ``<svg>...</svg>`` block; fall back to the raw
|
| 76 |
+
text so a render error (and its feedback) still flows back to the engine.
|
| 77 |
+
"""
|
| 78 |
+
m = _SVG_RE.search(candidate)
|
| 79 |
+
return m.group(0) if m else candidate.strip()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def render_image(svg_code: str) -> str:
|
| 83 |
+
"""Render SVG source to a base64-encoded PNG string."""
|
| 84 |
+
png_bytes = cairosvg.svg2png(bytestring=svg_code.encode("utf-8"))
|
| 85 |
+
return base64.b64encode(png_bytes).decode("utf-8")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def score_with_claude(image_b64: str, criteria: str) -> tuple[float, str]:
|
| 89 |
+
"""Show the rendered image to Claude Code and parse `SCORE: X/10` -> (0..1, text)."""
|
| 90 |
+
tmpdir = tempfile.mkdtemp(prefix="gepa_score_")
|
| 91 |
+
path = os.path.join(tmpdir, "candidate.png")
|
| 92 |
+
with open(path, "wb") as f:
|
| 93 |
+
f.write(base64.b64decode(image_b64))
|
| 94 |
+
prompt = (
|
| 95 |
+
f"{criteria}\n\n"
|
| 96 |
+
f"Open and look at the image, then give one or two sentences of concrete, "
|
| 97 |
+
f"actionable feedback on what to improve. End your reply with a line "
|
| 98 |
+
f"exactly of the form 'SCORE: X/10'.\n\nImage: @{path}"
|
| 99 |
+
)
|
| 100 |
+
text = _claude_cli(prompt)
|
| 101 |
+
m = re.search(r"SCORE:\s*([0-9]+(?:\.[0-9]+)?)\s*/\s*10", text, re.IGNORECASE)
|
| 102 |
+
score = (float(m.group(1)) / 10.0) if m else 0.0
|
| 103 |
+
return max(0.0, min(1.0, score)), text
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# ---------------------------------------------------------------------------
|
| 107 |
+
# Claude Code CLI as the reflection LM for the `gepa` engine.
|
| 108 |
+
# ---------------------------------------------------------------------------
|
| 109 |
+
def _claude_cli(prompt: str) -> str:
|
| 110 |
+
result = subprocess.run(
|
| 111 |
+
["claude", "-p", prompt],
|
| 112 |
+
capture_output=True, text=True, timeout=CLAUDE_TIMEOUT,
|
| 113 |
+
)
|
| 114 |
+
if result.returncode != 0:
|
| 115 |
+
raise RuntimeError(f"claude -p failed (code {result.returncode}): {result.stderr}")
|
| 116 |
+
return result.stdout
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _data_uri_to_file(url: str, tmpdir: str, idx: int) -> str | None:
|
| 120 |
+
"""Decode a `data:image/...;base64,...` URI to a temp file; return its path."""
|
| 121 |
+
if not url.startswith("data:"):
|
| 122 |
+
return None
|
| 123 |
+
header, _, b64 = url.partition(",")
|
| 124 |
+
ext = ".jpg" if "image/jpeg" in header else ".webp" if "image/webp" in header else ".png"
|
| 125 |
+
path = os.path.join(tmpdir, f"reflect_img_{idx}{ext}")
|
| 126 |
+
with open(path, "wb") as f:
|
| 127 |
+
f.write(base64.b64decode(b64))
|
| 128 |
+
return path
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def claude_reflection_lm(prompt):
|
| 132 |
+
"""Reflection LM backed by the `claude` CLI.
|
| 133 |
+
|
| 134 |
+
GEPA passes either a plain string (text-only reflective data) or an
|
| 135 |
+
OpenAI-style chat-messages list when images are present (our RenderedSVG).
|
| 136 |
+
We flatten to text and, for any inline image, write it to a temp PNG and
|
| 137 |
+
@-reference it so Claude Code can view it.
|
| 138 |
+
"""
|
| 139 |
+
if isinstance(prompt, str):
|
| 140 |
+
return _claude_cli(prompt)
|
| 141 |
+
|
| 142 |
+
text_parts: list[str] = []
|
| 143 |
+
img_paths: list[str] = []
|
| 144 |
+
tmpdir = tempfile.mkdtemp(prefix="gepa_claude_")
|
| 145 |
+
for msg in prompt:
|
| 146 |
+
content = msg.get("content", "")
|
| 147 |
+
if isinstance(content, str):
|
| 148 |
+
text_parts.append(content)
|
| 149 |
+
continue
|
| 150 |
+
for part in content:
|
| 151 |
+
if part.get("type") == "text":
|
| 152 |
+
text_parts.append(part.get("text", ""))
|
| 153 |
+
elif part.get("type") == "image_url":
|
| 154 |
+
path = _data_uri_to_file(
|
| 155 |
+
part["image_url"]["url"], tmpdir, len(img_paths) + 1
|
| 156 |
+
)
|
| 157 |
+
if path:
|
| 158 |
+
img_paths.append(path)
|
| 159 |
+
|
| 160 |
+
prompt_text = "\n\n".join(p for p in text_parts if p)
|
| 161 |
+
if img_paths:
|
| 162 |
+
refs = " ".join(f"@{p}" for p in img_paths)
|
| 163 |
+
prompt_text += (
|
| 164 |
+
"\n\nThe referenced image(s) are the rendered SVG(s) above — "
|
| 165 |
+
f"open and inspect them: {refs}"
|
| 166 |
+
)
|
| 167 |
+
return _claude_cli(prompt_text)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# ---------------------------------------------------------------------------
|
| 171 |
+
# Task definition — ONE evaluator, shared by every engine.
|
| 172 |
+
#
|
| 173 |
+
# In the omni layer the candidate is a plain SVG *string* (only the `gepa`
|
| 174 |
+
# engine accepts a multi-component dict seed; autoresearch/meta_harness require
|
| 175 |
+
# a single text). So `evaluate` takes the SVG string directly.
|
| 176 |
+
# ---------------------------------------------------------------------------
|
| 177 |
+
def evaluate(candidate, example):
|
| 178 |
+
"""Render SVG -> image, score with Claude Code, return (score, side_info)."""
|
| 179 |
+
svg = coerce_svg(candidate)
|
| 180 |
+
try:
|
| 181 |
+
image = render_image(svg)
|
| 182 |
+
except Exception as e:
|
| 183 |
+
# Give the engine actionable feedback instead of crashing the run.
|
| 184 |
+
return 0.0, {"Feedback": f"SVG failed to render ({type(e).__name__}): {e}"}
|
| 185 |
+
score, feedback = score_with_claude(image, example["criteria"])
|
| 186 |
+
return score, {
|
| 187 |
+
"RenderedSVG": Image(base64_data=image, media_type="image/png"),
|
| 188 |
+
"Feedback": feedback,
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
VISUAL_ASPECTS = [
|
| 193 |
+
# 6 visual aspects -> Pareto-efficient selection (gepa engine).
|
| 194 |
+
{"id": "overall", "criteria": f"Rate overall quality of this SVG ({GOAL}). SCORE: X/10"},
|
| 195 |
+
{"id": "anatomy", "criteria": "Rate pelican accuracy: beak, pouch, plumage. SCORE: X/10"},
|
| 196 |
+
{"id": "bicycle", "criteria": "Rate bicycle: wheels, frame, handlebars, pedals. SCORE: X/10"},
|
| 197 |
+
{"id": "composition", "criteria": "Rate how convincingly the pelican rides the bicycle. SCORE: X/10"},
|
| 198 |
+
{"id": "visual", "criteria": "Rate visual appeal, scenery, and color usage. SCORE: X/10"},
|
| 199 |
+
{"id": "craft", "criteria": "Rate SVG technical quality: shapes, layering. SCORE: X/10"},
|
| 200 |
+
]
|
| 201 |
+
|
| 202 |
+
OBJECTIVE = f"Optimize SVG code to illustrate '{GOAL}'. Output ONLY valid SVG."
|
| 203 |
+
BACKGROUND = (
|
| 204 |
+
"The candidate is raw SVG source. It is rendered to a PNG and graded 0-10 "
|
| 205 |
+
"by a vision model against several visual criteria (pelican anatomy, the "
|
| 206 |
+
"bicycle, the riding composition, appeal, and SVG craft). Higher is better. "
|
| 207 |
+
"Output ONLY a single valid <svg>...</svg> document."
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _gepa_config() -> OptimizeAnythingConfig:
|
| 212 |
+
"""The reflective-evolution engine, with Claude Code as its reflection LM.
|
| 213 |
+
|
| 214 |
+
``engine_config`` is forwarded verbatim as ``GEPAConfig(**engine_config)``
|
| 215 |
+
by the omni gepa engine, so we build real GEPAConfig sub-objects here.
|
| 216 |
+
"""
|
| 217 |
+
return OptimizeAnythingConfig(
|
| 218 |
+
engine="gepa",
|
| 219 |
+
max_evals=MAX_EVALS,
|
| 220 |
+
sandbox=SANDBOX,
|
| 221 |
+
engine_config=dict(
|
| 222 |
+
engine=EngineConfig(display_progress_bar=True),
|
| 223 |
+
reflection=ReflectionConfig(reflection_lm=claude_reflection_lm),
|
| 224 |
+
),
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def _agentic_config(engine: str) -> OptimizeAnythingConfig:
|
| 229 |
+
"""autoresearch / meta_harness — both spawn `claude --print` themselves."""
|
| 230 |
+
return OptimizeAnythingConfig(
|
| 231 |
+
engine=engine,
|
| 232 |
+
max_evals=MAX_EVALS,
|
| 233 |
+
sandbox=SANDBOX,
|
| 234 |
+
engine_config=dict(model=CLAUDE_MODEL),
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
if __name__ == "__main__":
|
| 239 |
+
seed_svg = open("seed.svg").read() # a plain white canvas
|
| 240 |
+
task = dict(
|
| 241 |
+
evaluator=evaluate,
|
| 242 |
+
dataset=VISUAL_ASPECTS,
|
| 243 |
+
objective=OBJECTIVE,
|
| 244 |
+
background=BACKGROUND,
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# -- Phase 1 (explore): run all three engines in parallel, keep the best. --
|
| 248 |
+
# NOTE: temporarily running ONLY the autoresearch engine — the gepa and
|
| 249 |
+
# meta_harness engines are commented out below.
|
| 250 |
+
print(f"\n=== Phase 1: explore (autoresearch only, "
|
| 251 |
+
f"max_evals={MAX_EVALS}, sandbox={SANDBOX}) ===")
|
| 252 |
+
explore = optimize_best_of(
|
| 253 |
+
seed_svg,
|
| 254 |
+
configs=[
|
| 255 |
+
# _gepa_config(),
|
| 256 |
+
_agentic_config("autoresearch"),
|
| 257 |
+
# _agentic_config("meta_harness"),
|
| 258 |
+
],
|
| 259 |
+
max_workers=3,
|
| 260 |
+
**task,
|
| 261 |
+
)
|
| 262 |
+
print(f"\nPhase 1 best score: {explore.best_score:.3f} "
|
| 263 |
+
f"({explore.total_evals} evals)")
|
| 264 |
+
|
| 265 |
+
# -- Phase 2 (continue): seed a fresh autoresearch run from the winner. --
|
| 266 |
+
print(f"\n=== Phase 2: continue with autoresearch, seeded from the phase-1 "
|
| 267 |
+
f"winner (max_evals={MAX_EVALS}) ===")
|
| 268 |
+
omni = optimize_anything(
|
| 269 |
+
explore.best_candidate,
|
| 270 |
+
config=_agentic_config("autoresearch"),
|
| 271 |
+
**task,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
best = omni if omni.best_score >= explore.best_score else explore
|
| 275 |
+
print(f"\n=== Done. best score: {best.best_score:.3f} ===")
|
| 276 |
+
print(coerce_svg(best.best_candidate))
|
optanything_rag_claudecode (1).py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""optimize_anything "omni" + Claude Code — RAG *answer-prompt* optimization.
|
| 2 |
+
|
| 3 |
+
A sibling of ``optanything_claudecode.py``. Same two-phase **omni-GEPA** pattern
|
| 4 |
+
(https://gepa-ai.github.io/gepa/blog/2026/07/22/optimize-anything-omni/), but the
|
| 5 |
+
task is prompt engineering for a **retrieval-augmented QA** system instead of
|
| 6 |
+
SVG drawing.
|
| 7 |
+
|
| 8 |
+
The key framing the user asked for: **the query and the retrieved content are
|
| 9 |
+
FIXED — retrieval is frozen. The ONLY thing being optimized is the prompt used
|
| 10 |
+
to answer the question.**
|
| 11 |
+
|
| 12 |
+
* The optimized artifact (the "candidate") is a single ANSWER-GENERATION
|
| 13 |
+
PROMPT — the instruction block that tells the model how to use the retrieved
|
| 14 |
+
context to answer. GEPA rewrites this string; nothing else moves.
|
| 15 |
+
* Each dataset row is a frozen (question, context, gold_answer) triple. The
|
| 16 |
+
context is a pre-retrieved bundle of passages that deliberately includes
|
| 17 |
+
distractors, and one row whose answer is *absent* from the context (so a
|
| 18 |
+
good prompt must abstain rather than hallucinate).
|
| 19 |
+
|
| 20 |
+
* PHASE 1 (explore) — ``optimize_best_of`` runs three engines in parallel and
|
| 21 |
+
keeps the single best answer-prompt:
|
| 22 |
+
- ``gepa`` : reflective evolution; its reflection LM is the
|
| 23 |
+
`claude` CLI (it reads each generated answer + the
|
| 24 |
+
judge's critique).
|
| 25 |
+
- ``autoresearch`` : a black-box research optimizer that spawns
|
| 26 |
+
``claude --print`` to iterate on the prompt.
|
| 27 |
+
- ``meta_harness`` : an iterative meta-optimizer, also Claude-driven.
|
| 28 |
+
* PHASE 2 (continue) — a fresh run is *seeded from the winner*. This
|
| 29 |
+
continuation-from-the-best is what the blog calls omni-GEPA.
|
| 30 |
+
|
| 31 |
+
SCORING for every engine goes through one evaluator: take the candidate prompt,
|
| 32 |
+
splice in the FIXED context + question, ask Claude Code to answer *grounded in
|
| 33 |
+
that context only*, then ask Claude Code to grade the answer against the gold
|
| 34 |
+
answer and parse ``SCORE: X/10``. The score + textual feedback (Actionable Side
|
| 35 |
+
Information) flows back to whichever engine asked for it.
|
| 36 |
+
|
| 37 |
+
Prereqs (identical to optanything_claudecode.py):
|
| 38 |
+
* `claude` CLI on PATH and authenticated (`claude -p "hi"` works).
|
| 39 |
+
* `bwrap` on PATH if GEPA_SANDBOX=1 (the default).
|
| 40 |
+
* gepa installed from git main (the "omni" API is unreleased as of 0.1.4);
|
| 41 |
+
see pyproject.toml.
|
| 42 |
+
|
| 43 |
+
Run: uv run python optanything_rag_claudecode.py
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
import os
|
| 47 |
+
import re
|
| 48 |
+
import subprocess
|
| 49 |
+
|
| 50 |
+
from gepa.optimize_anything import (
|
| 51 |
+
optimize_anything,
|
| 52 |
+
optimize_best_of,
|
| 53 |
+
OptimizeAnythingConfig,
|
| 54 |
+
)
|
| 55 |
+
from gepa.gepa_launcher import GEPAConfig, EngineConfig, ReflectionConfig
|
| 56 |
+
|
| 57 |
+
# Per-engine eval-server budget. Phase 1 spends this on EACH of the three
|
| 58 |
+
# engines (they run concurrently), phase 2 spends it once more.
|
| 59 |
+
MAX_EVALS = int(os.environ.get("GEPA_MAX_EVALS", "20"))
|
| 60 |
+
# Model the agentic engines pass to `claude --model`. An alias ("sonnet",
|
| 61 |
+
# "opus", "haiku") or a full id both work.
|
| 62 |
+
CLAUDE_MODEL = os.environ.get("GEPA_CLAUDE_MODEL", "sonnet")
|
| 63 |
+
CLAUDE_TIMEOUT = int(os.environ.get("GEPA_CLAUDE_TIMEOUT", "600"))
|
| 64 |
+
# The agentic engines jail their `claude` subprocess with bwrap by default.
|
| 65 |
+
SANDBOX = os.environ.get("GEPA_SANDBOX", "1") not in ("0", "false", "no", "")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ---------------------------------------------------------------------------
|
| 69 |
+
# The FROZEN RAG corpus + queries.
|
| 70 |
+
#
|
| 71 |
+
# In a real system these `context` strings come out of a retriever. Here they
|
| 72 |
+
# are pre-retrieved and hard-coded: retrieval is FIXED, so the optimizer can
|
| 73 |
+
# only improve how the model *reads* the context to answer — never what gets
|
| 74 |
+
# retrieved. The passages include distractors, and `nyquist` has NO supporting
|
| 75 |
+
# passage on purpose (its gold answer is an explicit "not in context" abstain).
|
| 76 |
+
#
|
| 77 |
+
# The corpus is split TRAIN / VAL. GEPA optimizes the prompt against the
|
| 78 |
+
# trainset and scores candidates on the held-out valset to pick the one that
|
| 79 |
+
# GENERALIZES — the winning prompt must work on questions/contexts it never
|
| 80 |
+
# trained on, not just overfit the training rows. The valset mirrors the same
|
| 81 |
+
# stresses (a distractor row + an abstain-required row) over UNSEEN content.
|
| 82 |
+
# ---------------------------------------------------------------------------
|
| 83 |
+
RAG_TRAINSET = [
|
| 84 |
+
{
|
| 85 |
+
"id": "capital",
|
| 86 |
+
"question": "What is the capital city mentioned for the Kingdom of Aldoria?",
|
| 87 |
+
"context": (
|
| 88 |
+
"[Doc 12] Aldoria is a mountainous kingdom. Its largest port is Vellmar.\n"
|
| 89 |
+
"[Doc 47] The seat of Aldorian government and its capital is the walled "
|
| 90 |
+
"city of Threnhold, founded 800 years ago.\n"
|
| 91 |
+
"[Doc 51] Neighbouring Corvane has its capital at Ashgate."
|
| 92 |
+
),
|
| 93 |
+
"gold_answer": "Threnhold.",
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"id": "multi_hop",
|
| 97 |
+
"question": "Who succeeded the ruler who commissioned the Great Aqueduct?",
|
| 98 |
+
"context": (
|
| 99 |
+
"[Doc 03] The Great Aqueduct was commissioned by Queen Maeve during her reign.\n"
|
| 100 |
+
"[Doc 09] Queen Maeve reigned for 31 years and was succeeded by her nephew, King Doran.\n"
|
| 101 |
+
"[Doc 22] King Doran later abdicated in favour of a council."
|
| 102 |
+
),
|
| 103 |
+
"gold_answer": "King Doran (Queen Maeve's nephew) succeeded her.",
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"id": "number",
|
| 107 |
+
"question": "How long did the siege of Threnhold last?",
|
| 108 |
+
"context": (
|
| 109 |
+
"[Doc 31] The siege of Threnhold began in spring and, after repeated assaults, "
|
| 110 |
+
"the walls held for exactly 214 days before the attackers withdrew.\n"
|
| 111 |
+
"[Doc 32] Threnhold's walls are 12 metres high."
|
| 112 |
+
),
|
| 113 |
+
"gold_answer": "214 days.",
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"id": "distractor",
|
| 117 |
+
"question": "What is Aldoria's chief export?",
|
| 118 |
+
"context": (
|
| 119 |
+
"[Doc 15] Aldoria is famous for its silver mines; refined silver is its chief export.\n"
|
| 120 |
+
"[Doc 16] Corvane, by contrast, exports mostly timber.\n"
|
| 121 |
+
"[Doc 17] Aldorian cuisine features salted fish from Vellmar."
|
| 122 |
+
),
|
| 123 |
+
"gold_answer": "Silver (refined silver).",
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"id": "nyquist",
|
| 127 |
+
# No passage supports this — a good answer prompt must ABSTAIN, not guess.
|
| 128 |
+
"question": "What is the population of Threnhold?",
|
| 129 |
+
"context": (
|
| 130 |
+
"[Doc 47] The seat of Aldorian government and its capital is the walled "
|
| 131 |
+
"city of Threnhold, founded 800 years ago.\n"
|
| 132 |
+
"[Doc 32] Threnhold's walls are 12 metres high."
|
| 133 |
+
),
|
| 134 |
+
"gold_answer": (
|
| 135 |
+
"The population is not stated in the provided context; a correct answer "
|
| 136 |
+
"must say the information is not available rather than guess a number."
|
| 137 |
+
),
|
| 138 |
+
},
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
# Held-out validation set — UNSEEN questions over UNSEEN content. GEPA never
|
| 142 |
+
# optimizes against these; they are used only to score candidates for
|
| 143 |
+
# generalization, so the winning prompt is the one that transfers, not the one
|
| 144 |
+
# that memorised the trainset. Same stress mix: a distractor row (`val_export`)
|
| 145 |
+
# and an abstain-required row (`val_abstain`).
|
| 146 |
+
RAG_VALSET = [
|
| 147 |
+
{
|
| 148 |
+
"id": "val_capital",
|
| 149 |
+
"question": "Which city is the capital of Corvane?",
|
| 150 |
+
"context": (
|
| 151 |
+
"[Doc 51] Neighbouring Corvane has its capital at Ashgate.\n"
|
| 152 |
+
"[Doc 63] Corvane's largest festival is held each autumn in the town of Brill.\n"
|
| 153 |
+
"[Doc 64] Ashgate sits at the mouth of the River Corve."
|
| 154 |
+
),
|
| 155 |
+
"gold_answer": "Ashgate.",
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"id": "val_number",
|
| 159 |
+
"question": "How many towers does Ashgate castle have?",
|
| 160 |
+
"context": (
|
| 161 |
+
"[Doc 70] Ashgate castle is ringed by a moat and defended by nine towers.\n"
|
| 162 |
+
"[Doc 71] The castle's great hall seats three hundred."
|
| 163 |
+
),
|
| 164 |
+
"gold_answer": "Nine towers.",
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"id": "val_export",
|
| 168 |
+
"question": "What does Corvane mainly export?",
|
| 169 |
+
"context": (
|
| 170 |
+
"[Doc 16] Corvane exports mostly timber from its northern forests.\n"
|
| 171 |
+
"[Doc 15] Aldoria, by contrast, is famous for silver.\n"
|
| 172 |
+
"[Doc 17] Corvane also brews a well-known cider."
|
| 173 |
+
),
|
| 174 |
+
"gold_answer": "Timber.",
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"id": "val_abstain",
|
| 178 |
+
# No passage gives the founding year — the prompt must ABSTAIN.
|
| 179 |
+
"question": "In what year was Ashgate castle built?",
|
| 180 |
+
"context": (
|
| 181 |
+
"[Doc 70] Ashgate castle is ringed by a moat and defended by nine towers.\n"
|
| 182 |
+
"[Doc 64] Ashgate sits at the mouth of the River Corve."
|
| 183 |
+
),
|
| 184 |
+
"gold_answer": (
|
| 185 |
+
"The founding year is not stated in the provided context; a correct "
|
| 186 |
+
"answer must say the information is not available rather than guess."
|
| 187 |
+
),
|
| 188 |
+
},
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# ---------------------------------------------------------------------------
|
| 193 |
+
# Claude Code CLI helper (shared by the answerer, the judge, and — for the
|
| 194 |
+
# `gepa` engine — the reflection LM).
|
| 195 |
+
# ---------------------------------------------------------------------------
|
| 196 |
+
def _claude_cli(prompt: str) -> str:
|
| 197 |
+
result = subprocess.run(
|
| 198 |
+
["claude", "-p", prompt],
|
| 199 |
+
capture_output=True, text=True, timeout=CLAUDE_TIMEOUT,
|
| 200 |
+
)
|
| 201 |
+
if result.returncode != 0:
|
| 202 |
+
raise RuntimeError(f"claude -p failed (code {result.returncode}): {result.stderr}")
|
| 203 |
+
return result.stdout
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def claude_reflection_lm(prompt):
|
| 207 |
+
"""Reflection LM backed by the `claude` CLI (text-only for this task)."""
|
| 208 |
+
if isinstance(prompt, str):
|
| 209 |
+
return _claude_cli(prompt)
|
| 210 |
+
# Flatten any chat-messages form to plain text (no images here).
|
| 211 |
+
parts: list[str] = []
|
| 212 |
+
for msg in prompt:
|
| 213 |
+
content = msg.get("content", "")
|
| 214 |
+
if isinstance(content, str):
|
| 215 |
+
parts.append(content)
|
| 216 |
+
else:
|
| 217 |
+
for part in content:
|
| 218 |
+
if part.get("type") == "text":
|
| 219 |
+
parts.append(part.get("text", ""))
|
| 220 |
+
return _claude_cli("\n\n".join(p for p in parts if p))
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
# ---------------------------------------------------------------------------
|
| 224 |
+
# The candidate is a plain-text answer prompt. The agentic engines return
|
| 225 |
+
# whatever `claude` wrote — sometimes wrapped in ``` fences or prefaced with
|
| 226 |
+
# prose ("Here is the improved prompt:"). Strip fences; otherwise use as-is.
|
| 227 |
+
# ---------------------------------------------------------------------------
|
| 228 |
+
_FENCE_RE = re.compile(r"^```[a-zA-Z]*\n(.*?)\n```", re.DOTALL | re.MULTILINE)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def coerce_prompt(candidate: str) -> str:
|
| 232 |
+
"""Pull the answer prompt out of a candidate string."""
|
| 233 |
+
m = _FENCE_RE.search(candidate)
|
| 234 |
+
return (m.group(1) if m else candidate).strip()
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# ---------------------------------------------------------------------------
|
| 238 |
+
# Answer generation + grading, both via Claude Code.
|
| 239 |
+
# ---------------------------------------------------------------------------
|
| 240 |
+
def generate_answer(answer_prompt: str, question: str, context: str) -> str:
|
| 241 |
+
"""Run the candidate answer-prompt against the FIXED context + question."""
|
| 242 |
+
full = (
|
| 243 |
+
f"{answer_prompt}\n\n"
|
| 244 |
+
f"=== RETRIEVED CONTEXT (do not use outside knowledge) ===\n{context}\n\n"
|
| 245 |
+
f"=== QUESTION ===\n{question}\n\n"
|
| 246 |
+
f"=== ANSWER ==="
|
| 247 |
+
)
|
| 248 |
+
return _claude_cli(full).strip()
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def grade_answer(question: str, gold: str, answer: str) -> tuple[float, str]:
|
| 252 |
+
"""LLM-judge the generated answer against the gold answer -> (0..1, text)."""
|
| 253 |
+
prompt = (
|
| 254 |
+
"You are grading a retrieval-augmented QA system's answer.\n\n"
|
| 255 |
+
f"QUESTION:\n{question}\n\n"
|
| 256 |
+
f"REFERENCE (gold) ANSWER:\n{gold}\n\n"
|
| 257 |
+
f"SYSTEM ANSWER:\n{answer}\n\n"
|
| 258 |
+
"Grade the system answer for factual correctness and grounding relative "
|
| 259 |
+
"to the reference. Full marks require the right fact (or a correct "
|
| 260 |
+
"abstention when the reference says the info is unavailable), concisely "
|
| 261 |
+
"stated and grounded in the context. Penalise hallucinations, hedging, "
|
| 262 |
+
"and answering when the reference says to abstain.\n"
|
| 263 |
+
"Give one or two sentences of concrete, actionable feedback on how the "
|
| 264 |
+
"ANSWER PROMPT could be rewritten to fix what went wrong, then end with a "
|
| 265 |
+
"line exactly of the form 'SCORE: X/10'."
|
| 266 |
+
)
|
| 267 |
+
text = _claude_cli(prompt)
|
| 268 |
+
m = re.search(r"SCORE:\s*([0-9]+(?:\.[0-9]+)?)\s*/\s*10", text, re.IGNORECASE)
|
| 269 |
+
score = (float(m.group(1)) / 10.0) if m else 0.0
|
| 270 |
+
return max(0.0, min(1.0, score)), text
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# ---------------------------------------------------------------------------
|
| 274 |
+
# Task definition — ONE evaluator, shared by every engine.
|
| 275 |
+
#
|
| 276 |
+
# `candidate` is the answer-generation prompt string. `example` is one frozen
|
| 277 |
+
# (question, context, gold_answer) row.
|
| 278 |
+
# ---------------------------------------------------------------------------
|
| 279 |
+
def evaluate(candidate, example):
|
| 280 |
+
"""Answer the FIXED query with the candidate prompt, then grade it."""
|
| 281 |
+
answer_prompt = coerce_prompt(candidate)
|
| 282 |
+
try:
|
| 283 |
+
answer = generate_answer(answer_prompt, example["question"], example["context"])
|
| 284 |
+
except Exception as e:
|
| 285 |
+
return 0.0, {"Feedback": f"Answer generation failed ({type(e).__name__}): {e}"}
|
| 286 |
+
score, feedback = grade_answer(example["question"], example["gold_answer"], answer)
|
| 287 |
+
return score, {
|
| 288 |
+
# The generated answer is the actionable side-info the reflection LM
|
| 289 |
+
# reads to understand *why* this prompt scored what it did.
|
| 290 |
+
"GeneratedAnswer": answer,
|
| 291 |
+
"Feedback": feedback,
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
OBJECTIVE = (
|
| 296 |
+
"Optimize the ANSWER PROMPT for a retrieval-augmented QA system. Retrieval "
|
| 297 |
+
"is fixed; only the prompt that instructs the model how to answer from the "
|
| 298 |
+
"retrieved context may change. Output ONLY the prompt text."
|
| 299 |
+
)
|
| 300 |
+
BACKGROUND = (
|
| 301 |
+
"The candidate is a reusable ANSWER PROMPT. At eval time it is concatenated "
|
| 302 |
+
"with a FROZEN retrieved-context bundle and a question, and a model produces "
|
| 303 |
+
"an answer strictly from that context. A judge grades the answer 0-10 "
|
| 304 |
+
"against a gold reference for factual correctness and grounding. The corpus "
|
| 305 |
+
"contains distractor passages and at least one question whose answer is NOT "
|
| 306 |
+
"in the context — for that one a correct answer must ABSTAIN ('not stated in "
|
| 307 |
+
"the context') rather than hallucinate. A good prompt therefore enforces: "
|
| 308 |
+
"answer only from the context, cite/quote support, be concise, and abstain "
|
| 309 |
+
"when the context lacks the answer. Output ONLY the prompt text."
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
# A deliberately weak seed prompt — it neither grounds nor abstains, so there is
|
| 313 |
+
# room for the optimizer to improve it.
|
| 314 |
+
SEED_PROMPT = "Answer the question."
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def _gepa_config() -> OptimizeAnythingConfig:
|
| 318 |
+
"""Reflective-evolution engine, with Claude Code as its reflection LM."""
|
| 319 |
+
return OptimizeAnythingConfig(
|
| 320 |
+
engine="gepa",
|
| 321 |
+
max_evals=MAX_EVALS,
|
| 322 |
+
sandbox=SANDBOX,
|
| 323 |
+
engine_config=dict(
|
| 324 |
+
engine=EngineConfig(display_progress_bar=True),
|
| 325 |
+
reflection=ReflectionConfig(reflection_lm=claude_reflection_lm),
|
| 326 |
+
),
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _agentic_config(engine: str) -> OptimizeAnythingConfig:
|
| 331 |
+
"""autoresearch / meta_harness — both spawn `claude --print` themselves."""
|
| 332 |
+
return OptimizeAnythingConfig(
|
| 333 |
+
engine=engine,
|
| 334 |
+
max_evals=MAX_EVALS,
|
| 335 |
+
sandbox=SANDBOX,
|
| 336 |
+
engine_config=dict(model=CLAUDE_MODEL),
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
if __name__ == "__main__":
|
| 341 |
+
task = dict(
|
| 342 |
+
evaluator=evaluate,
|
| 343 |
+
dataset=RAG_TRAINSET,
|
| 344 |
+
valset=RAG_VALSET,
|
| 345 |
+
objective=OBJECTIVE,
|
| 346 |
+
background=BACKGROUND,
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# -- Phase 1 (explore): run engines in parallel, keep the best prompt. --
|
| 350 |
+
# Mirroring optanything_claudecode.py, only the autoresearch engine is
|
| 351 |
+
# enabled by default; uncomment the others to run the full best-of-three.
|
| 352 |
+
print(f"\n=== Phase 1: explore (autoresearch only, "
|
| 353 |
+
f"max_evals={MAX_EVALS}, sandbox={SANDBOX}) ===")
|
| 354 |
+
explore = optimize_best_of(
|
| 355 |
+
SEED_PROMPT,
|
| 356 |
+
configs=[
|
| 357 |
+
# _gepa_config(),
|
| 358 |
+
_agentic_config("autoresearch"),
|
| 359 |
+
# _agentic_config("meta_harness"),
|
| 360 |
+
],
|
| 361 |
+
max_workers=3,
|
| 362 |
+
**task,
|
| 363 |
+
)
|
| 364 |
+
print(f"\nPhase 1 best score: {explore.best_score:.3f} "
|
| 365 |
+
f"({explore.total_evals} evals)")
|
| 366 |
+
|
| 367 |
+
# -- Phase 2 (continue): seed a fresh run from the winner. --
|
| 368 |
+
print(f"\n=== Phase 2: continue with autoresearch, seeded from the phase-1 "
|
| 369 |
+
f"winner (max_evals={MAX_EVALS}) ===")
|
| 370 |
+
omni = optimize_anything(
|
| 371 |
+
explore.best_candidate,
|
| 372 |
+
config=_agentic_config("autoresearch"),
|
| 373 |
+
**task,
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
best = omni if omni.best_score >= explore.best_score else explore
|
| 377 |
+
print(f"\n=== Done. best score: {best.best_score:.3f} ===")
|
| 378 |
+
print("\n--- Optimized answer prompt ---")
|
| 379 |
+
print(coerce_prompt(best.best_candidate))
|
optanything_rag_claudecode.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""optimize_anything "omni" + Claude Code — RAG *answer-prompt* optimization.
|
| 2 |
+
|
| 3 |
+
A sibling of ``optanything_claudecode.py``. Same two-phase **omni-GEPA** pattern
|
| 4 |
+
(https://gepa-ai.github.io/gepa/blog/2026/07/22/optimize-anything-omni/), but the
|
| 5 |
+
task is prompt engineering for a **retrieval-augmented QA** system instead of
|
| 6 |
+
SVG drawing.
|
| 7 |
+
|
| 8 |
+
The key framing the user asked for: **the query and the retrieved content are
|
| 9 |
+
FIXED — retrieval is frozen. The ONLY thing being optimized is the prompt used
|
| 10 |
+
to answer the question.**
|
| 11 |
+
|
| 12 |
+
* The optimized artifact (the "candidate") is a single ANSWER-GENERATION
|
| 13 |
+
PROMPT — the instruction block that tells the model how to use the retrieved
|
| 14 |
+
context to answer. GEPA rewrites this string; nothing else moves.
|
| 15 |
+
* Each dataset row is a frozen (question, context, gold_answer) triple. The
|
| 16 |
+
context is a pre-retrieved bundle of passages that deliberately includes
|
| 17 |
+
distractors, and one row whose answer is *absent* from the context (so a
|
| 18 |
+
good prompt must abstain rather than hallucinate).
|
| 19 |
+
|
| 20 |
+
* PHASE 1 (explore) — ``optimize_best_of`` runs three engines in parallel and
|
| 21 |
+
keeps the single best answer-prompt:
|
| 22 |
+
- ``gepa`` : reflective evolution; its reflection LM is the
|
| 23 |
+
`claude` CLI (it reads each generated answer + the
|
| 24 |
+
judge's critique).
|
| 25 |
+
- ``autoresearch`` : a black-box research optimizer that spawns
|
| 26 |
+
``claude --print`` to iterate on the prompt.
|
| 27 |
+
- ``meta_harness`` : an iterative meta-optimizer, also Claude-driven.
|
| 28 |
+
* PHASE 2 (continue) — a fresh run is *seeded from the winner*. This
|
| 29 |
+
continuation-from-the-best is what the blog calls omni-GEPA.
|
| 30 |
+
|
| 31 |
+
SCORING for every engine goes through one evaluator: take the candidate prompt,
|
| 32 |
+
splice in the FIXED context + question, ask Claude Code to answer *grounded in
|
| 33 |
+
that context only*, then ask Claude Code to grade the answer against the gold
|
| 34 |
+
answer and parse ``SCORE: X/10``. The score + textual feedback (Actionable Side
|
| 35 |
+
Information) flows back to whichever engine asked for it.
|
| 36 |
+
|
| 37 |
+
Prereqs (identical to optanything_claudecode.py):
|
| 38 |
+
* `claude` CLI on PATH and authenticated (`claude -p "hi"` works).
|
| 39 |
+
* `bwrap` on PATH if GEPA_SANDBOX=1 (the default).
|
| 40 |
+
* gepa installed from git main (the "omni" API is unreleased as of 0.1.4);
|
| 41 |
+
see pyproject.toml.
|
| 42 |
+
|
| 43 |
+
Run: uv run python optanything_rag_claudecode.py
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
import os
|
| 47 |
+
import re
|
| 48 |
+
import subprocess
|
| 49 |
+
|
| 50 |
+
from gepa.optimize_anything import (
|
| 51 |
+
optimize_anything,
|
| 52 |
+
optimize_best_of,
|
| 53 |
+
OptimizeAnythingConfig,
|
| 54 |
+
)
|
| 55 |
+
from gepa.gepa_launcher import GEPAConfig, EngineConfig, ReflectionConfig
|
| 56 |
+
|
| 57 |
+
# Per-engine eval-server budget. Phase 1 spends this on EACH of the three
|
| 58 |
+
# engines (they run concurrently), phase 2 spends it once more.
|
| 59 |
+
MAX_EVALS = int(os.environ.get("GEPA_MAX_EVALS", "20"))
|
| 60 |
+
# Model the agentic engines pass to `claude --model`. An alias ("sonnet",
|
| 61 |
+
# "opus", "haiku") or a full id both work.
|
| 62 |
+
CLAUDE_MODEL = os.environ.get("GEPA_CLAUDE_MODEL", "sonnet")
|
| 63 |
+
CLAUDE_TIMEOUT = int(os.environ.get("GEPA_CLAUDE_TIMEOUT", "600"))
|
| 64 |
+
# The agentic engines jail their `claude` subprocess with bwrap by default.
|
| 65 |
+
SANDBOX = os.environ.get("GEPA_SANDBOX", "1") not in ("0", "false", "no", "")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ---------------------------------------------------------------------------
|
| 69 |
+
# The FROZEN RAG corpus + queries.
|
| 70 |
+
#
|
| 71 |
+
# In a real system these `context` strings come out of a retriever. Here they
|
| 72 |
+
# are pre-retrieved and hard-coded: retrieval is FIXED, so the optimizer can
|
| 73 |
+
# only improve how the model *reads* the context to answer — never what gets
|
| 74 |
+
# retrieved. The passages include distractors, and `nyquist` has NO supporting
|
| 75 |
+
# passage on purpose (its gold answer is an explicit "not in context" abstain).
|
| 76 |
+
#
|
| 77 |
+
# The corpus is split TRAIN / VAL. GEPA optimizes the prompt against the
|
| 78 |
+
# trainset and scores candidates on the held-out valset to pick the one that
|
| 79 |
+
# GENERALIZES — the winning prompt must work on questions/contexts it never
|
| 80 |
+
# trained on, not just overfit the training rows. The valset mirrors the same
|
| 81 |
+
# stresses (a distractor row + an abstain-required row) over UNSEEN content.
|
| 82 |
+
# ---------------------------------------------------------------------------
|
| 83 |
+
RAG_TRAINSET = [
|
| 84 |
+
{
|
| 85 |
+
"id": "capital",
|
| 86 |
+
"question": "What is the capital city mentioned for the Kingdom of Aldoria?",
|
| 87 |
+
"context": (
|
| 88 |
+
"[Doc 12] Aldoria is a mountainous kingdom. Its largest port is Vellmar.\n"
|
| 89 |
+
"[Doc 47] The seat of Aldorian government and its capital is the walled "
|
| 90 |
+
"city of Threnhold, founded 800 years ago.\n"
|
| 91 |
+
"[Doc 51] Neighbouring Corvane has its capital at Ashgate."
|
| 92 |
+
),
|
| 93 |
+
"gold_answer": "Threnhold.",
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"id": "multi_hop",
|
| 97 |
+
"question": "Who succeeded the ruler who commissioned the Great Aqueduct?",
|
| 98 |
+
"context": (
|
| 99 |
+
"[Doc 03] The Great Aqueduct was commissioned by Queen Maeve during her reign.\n"
|
| 100 |
+
"[Doc 09] Queen Maeve reigned for 31 years and was succeeded by her nephew, King Doran.\n"
|
| 101 |
+
"[Doc 22] King Doran later abdicated in favour of a council."
|
| 102 |
+
),
|
| 103 |
+
"gold_answer": "King Doran (Queen Maeve's nephew) succeeded her.",
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"id": "number",
|
| 107 |
+
"question": "How long did the siege of Threnhold last?",
|
| 108 |
+
"context": (
|
| 109 |
+
"[Doc 31] The siege of Threnhold began in spring and, after repeated assaults, "
|
| 110 |
+
"the walls held for exactly 214 days before the attackers withdrew.\n"
|
| 111 |
+
"[Doc 32] Threnhold's walls are 12 metres high."
|
| 112 |
+
),
|
| 113 |
+
"gold_answer": "214 days.",
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"id": "distractor",
|
| 117 |
+
"question": "What is Aldoria's chief export?",
|
| 118 |
+
"context": (
|
| 119 |
+
"[Doc 15] Aldoria is famous for its silver mines; refined silver is its chief export.\n"
|
| 120 |
+
"[Doc 16] Corvane, by contrast, exports mostly timber.\n"
|
| 121 |
+
"[Doc 17] Aldorian cuisine features salted fish from Vellmar."
|
| 122 |
+
),
|
| 123 |
+
"gold_answer": "Silver (refined silver).",
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"id": "nyquist",
|
| 127 |
+
# No passage supports this — a good answer prompt must ABSTAIN, not guess.
|
| 128 |
+
"question": "What is the population of Threnhold?",
|
| 129 |
+
"context": (
|
| 130 |
+
"[Doc 47] The seat of Aldorian government and its capital is the walled "
|
| 131 |
+
"city of Threnhold, founded 800 years ago.\n"
|
| 132 |
+
"[Doc 32] Threnhold's walls are 12 metres high."
|
| 133 |
+
),
|
| 134 |
+
"gold_answer": (
|
| 135 |
+
"The population is not stated in the provided context; a correct answer "
|
| 136 |
+
"must say the information is not available rather than guess a number."
|
| 137 |
+
),
|
| 138 |
+
},
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
# Held-out validation set — UNSEEN questions over UNSEEN content. GEPA never
|
| 142 |
+
# optimizes against these; they are used only to score candidates for
|
| 143 |
+
# generalization, so the winning prompt is the one that transfers, not the one
|
| 144 |
+
# that memorised the trainset. Same stress mix: a distractor row (`val_export`)
|
| 145 |
+
# and an abstain-required row (`val_abstain`).
|
| 146 |
+
RAG_VALSET = [
|
| 147 |
+
{
|
| 148 |
+
"id": "val_capital",
|
| 149 |
+
"question": "Which city is the capital of Corvane?",
|
| 150 |
+
"context": (
|
| 151 |
+
"[Doc 51] Neighbouring Corvane has its capital at Ashgate.\n"
|
| 152 |
+
"[Doc 63] Corvane's largest festival is held each autumn in the town of Brill.\n"
|
| 153 |
+
"[Doc 64] Ashgate sits at the mouth of the River Corve."
|
| 154 |
+
),
|
| 155 |
+
"gold_answer": "Ashgate.",
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"id": "val_number",
|
| 159 |
+
"question": "How many towers does Ashgate castle have?",
|
| 160 |
+
"context": (
|
| 161 |
+
"[Doc 70] Ashgate castle is ringed by a moat and defended by nine towers.\n"
|
| 162 |
+
"[Doc 71] The castle's great hall seats three hundred."
|
| 163 |
+
),
|
| 164 |
+
"gold_answer": "Nine towers.",
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"id": "val_export",
|
| 168 |
+
"question": "What does Corvane mainly export?",
|
| 169 |
+
"context": (
|
| 170 |
+
"[Doc 16] Corvane exports mostly timber from its northern forests.\n"
|
| 171 |
+
"[Doc 15] Aldoria, by contrast, is famous for silver.\n"
|
| 172 |
+
"[Doc 17] Corvane also brews a well-known cider."
|
| 173 |
+
),
|
| 174 |
+
"gold_answer": "Timber.",
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"id": "val_abstain",
|
| 178 |
+
# No passage gives the founding year — the prompt must ABSTAIN.
|
| 179 |
+
"question": "In what year was Ashgate castle built?",
|
| 180 |
+
"context": (
|
| 181 |
+
"[Doc 70] Ashgate castle is ringed by a moat and defended by nine towers.\n"
|
| 182 |
+
"[Doc 64] Ashgate sits at the mouth of the River Corve."
|
| 183 |
+
),
|
| 184 |
+
"gold_answer": (
|
| 185 |
+
"The founding year is not stated in the provided context; a correct "
|
| 186 |
+
"answer must say the information is not available rather than guess."
|
| 187 |
+
),
|
| 188 |
+
},
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# ---------------------------------------------------------------------------
|
| 193 |
+
# Claude Code CLI helper (shared by the answerer, the judge, and — for the
|
| 194 |
+
# `gepa` engine — the reflection LM).
|
| 195 |
+
# ---------------------------------------------------------------------------
|
| 196 |
+
def _claude_cli(prompt: str) -> str:
|
| 197 |
+
result = subprocess.run(
|
| 198 |
+
["claude", "-p", prompt],
|
| 199 |
+
capture_output=True, text=True, timeout=CLAUDE_TIMEOUT,
|
| 200 |
+
)
|
| 201 |
+
if result.returncode != 0:
|
| 202 |
+
raise RuntimeError(f"claude -p failed (code {result.returncode}): {result.stderr}")
|
| 203 |
+
return result.stdout
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def claude_reflection_lm(prompt):
|
| 207 |
+
"""Reflection LM backed by the `claude` CLI (text-only for this task)."""
|
| 208 |
+
if isinstance(prompt, str):
|
| 209 |
+
return _claude_cli(prompt)
|
| 210 |
+
# Flatten any chat-messages form to plain text (no images here).
|
| 211 |
+
parts: list[str] = []
|
| 212 |
+
for msg in prompt:
|
| 213 |
+
content = msg.get("content", "")
|
| 214 |
+
if isinstance(content, str):
|
| 215 |
+
parts.append(content)
|
| 216 |
+
else:
|
| 217 |
+
for part in content:
|
| 218 |
+
if part.get("type") == "text":
|
| 219 |
+
parts.append(part.get("text", ""))
|
| 220 |
+
return _claude_cli("\n\n".join(p for p in parts if p))
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
# ---------------------------------------------------------------------------
|
| 224 |
+
# The candidate is a plain-text answer prompt. The agentic engines return
|
| 225 |
+
# whatever `claude` wrote — sometimes wrapped in ``` fences or prefaced with
|
| 226 |
+
# prose ("Here is the improved prompt:"). Strip fences; otherwise use as-is.
|
| 227 |
+
# ---------------------------------------------------------------------------
|
| 228 |
+
_FENCE_RE = re.compile(r"^```[a-zA-Z]*\n(.*?)\n```", re.DOTALL | re.MULTILINE)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def coerce_prompt(candidate: str) -> str:
|
| 232 |
+
"""Pull the answer prompt out of a candidate string."""
|
| 233 |
+
m = _FENCE_RE.search(candidate)
|
| 234 |
+
return (m.group(1) if m else candidate).strip()
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# ---------------------------------------------------------------------------
|
| 238 |
+
# Answer generation + grading, both via Claude Code.
|
| 239 |
+
# ---------------------------------------------------------------------------
|
| 240 |
+
def generate_answer(answer_prompt: str, question: str, context: str) -> str:
|
| 241 |
+
"""Run the candidate answer-prompt against the FIXED context + question."""
|
| 242 |
+
full = (
|
| 243 |
+
f"{answer_prompt}\n\n"
|
| 244 |
+
f"=== RETRIEVED CONTEXT (do not use outside knowledge) ===\n{context}\n\n"
|
| 245 |
+
f"=== QUESTION ===\n{question}\n\n"
|
| 246 |
+
f"=== ANSWER ==="
|
| 247 |
+
)
|
| 248 |
+
return _claude_cli(full).strip()
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def grade_answer(question: str, gold: str, answer: str) -> tuple[float, str]:
|
| 252 |
+
"""LLM-judge the generated answer against the gold answer -> (0..1, text)."""
|
| 253 |
+
prompt = (
|
| 254 |
+
"You are grading a retrieval-augmented QA system's answer.\n\n"
|
| 255 |
+
f"QUESTION:\n{question}\n\n"
|
| 256 |
+
f"REFERENCE (gold) ANSWER:\n{gold}\n\n"
|
| 257 |
+
f"SYSTEM ANSWER:\n{answer}\n\n"
|
| 258 |
+
"Grade the system answer for factual correctness and grounding relative "
|
| 259 |
+
"to the reference. Full marks require the right fact (or a correct "
|
| 260 |
+
"abstention when the reference says the info is unavailable), concisely "
|
| 261 |
+
"stated and grounded in the context. Penalise hallucinations, hedging, "
|
| 262 |
+
"and answering when the reference says to abstain.\n"
|
| 263 |
+
"Give one or two sentences of concrete, actionable feedback on how the "
|
| 264 |
+
"ANSWER PROMPT could be rewritten to fix what went wrong, then end with a "
|
| 265 |
+
"line exactly of the form 'SCORE: X/10'."
|
| 266 |
+
)
|
| 267 |
+
text = _claude_cli(prompt)
|
| 268 |
+
m = re.search(r"SCORE:\s*([0-9]+(?:\.[0-9]+)?)\s*/\s*10", text, re.IGNORECASE)
|
| 269 |
+
score = (float(m.group(1)) / 10.0) if m else 0.0
|
| 270 |
+
return max(0.0, min(1.0, score)), text
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# ---------------------------------------------------------------------------
|
| 274 |
+
# Task definition — ONE evaluator, shared by every engine.
|
| 275 |
+
#
|
| 276 |
+
# `candidate` is the answer-generation prompt string. `example` is one frozen
|
| 277 |
+
# (question, context, gold_answer) row.
|
| 278 |
+
# ---------------------------------------------------------------------------
|
| 279 |
+
def evaluate(candidate, example):
|
| 280 |
+
"""Answer the FIXED query with the candidate prompt, then grade it."""
|
| 281 |
+
answer_prompt = coerce_prompt(candidate)
|
| 282 |
+
try:
|
| 283 |
+
answer = generate_answer(answer_prompt, example["question"], example["context"])
|
| 284 |
+
except Exception as e:
|
| 285 |
+
return 0.0, {"Feedback": f"Answer generation failed ({type(e).__name__}): {e}"}
|
| 286 |
+
score, feedback = grade_answer(example["question"], example["gold_answer"], answer)
|
| 287 |
+
return score, {
|
| 288 |
+
# The generated answer is the actionable side-info the reflection LM
|
| 289 |
+
# reads to understand *why* this prompt scored what it did.
|
| 290 |
+
"GeneratedAnswer": answer,
|
| 291 |
+
"Feedback": feedback,
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
OBJECTIVE = (
|
| 296 |
+
"Optimize the ANSWER PROMPT for a retrieval-augmented QA system. Retrieval "
|
| 297 |
+
"is fixed; only the prompt that instructs the model how to answer from the "
|
| 298 |
+
"retrieved context may change. Output ONLY the prompt text."
|
| 299 |
+
)
|
| 300 |
+
BACKGROUND = (
|
| 301 |
+
"The candidate is a reusable ANSWER PROMPT. At eval time it is concatenated "
|
| 302 |
+
"with a FROZEN retrieved-context bundle and a question, and a model produces "
|
| 303 |
+
"an answer strictly from that context. A judge grades the answer 0-10 "
|
| 304 |
+
"against a gold reference for factual correctness and grounding. The corpus "
|
| 305 |
+
"contains distractor passages and at least one question whose answer is NOT "
|
| 306 |
+
"in the context — for that one a correct answer must ABSTAIN ('not stated in "
|
| 307 |
+
"the context') rather than hallucinate. A good prompt therefore enforces: "
|
| 308 |
+
"answer only from the context, cite/quote support, be concise, and abstain "
|
| 309 |
+
"when the context lacks the answer. Output ONLY the prompt text."
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
# A deliberately weak seed prompt — it neither grounds nor abstains, so there is
|
| 313 |
+
# room for the optimizer to improve it.
|
| 314 |
+
SEED_PROMPT = "Answer the question."
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def _gepa_config() -> OptimizeAnythingConfig:
|
| 318 |
+
"""Reflective-evolution engine, with Claude Code as its reflection LM."""
|
| 319 |
+
return OptimizeAnythingConfig(
|
| 320 |
+
engine="gepa",
|
| 321 |
+
max_evals=MAX_EVALS,
|
| 322 |
+
sandbox=SANDBOX,
|
| 323 |
+
engine_config=dict(
|
| 324 |
+
engine=EngineConfig(display_progress_bar=True),
|
| 325 |
+
reflection=ReflectionConfig(reflection_lm=claude_reflection_lm),
|
| 326 |
+
),
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _agentic_config(engine: str) -> OptimizeAnythingConfig:
|
| 331 |
+
"""autoresearch / meta_harness — both spawn `claude --print` themselves."""
|
| 332 |
+
return OptimizeAnythingConfig(
|
| 333 |
+
engine=engine,
|
| 334 |
+
max_evals=MAX_EVALS,
|
| 335 |
+
sandbox=SANDBOX,
|
| 336 |
+
engine_config=dict(model=CLAUDE_MODEL),
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
if __name__ == "__main__":
|
| 341 |
+
task = dict(
|
| 342 |
+
evaluator=evaluate,
|
| 343 |
+
dataset=RAG_DATASET,
|
| 344 |
+
objective=OBJECTIVE,
|
| 345 |
+
background=BACKGROUND,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
# -- Phase 1 (explore): run engines in parallel, keep the best prompt. --
|
| 349 |
+
# Mirroring optanything_claudecode.py, only the autoresearch engine is
|
| 350 |
+
# enabled by default; uncomment the others to run the full best-of-three.
|
| 351 |
+
print(f"\n=== Phase 1: explore (autoresearch only, "
|
| 352 |
+
f"max_evals={MAX_EVALS}, sandbox={SANDBOX}) ===")
|
| 353 |
+
explore = optimize_best_of(
|
| 354 |
+
SEED_PROMPT,
|
| 355 |
+
configs=[
|
| 356 |
+
# _gepa_config(),
|
| 357 |
+
_agentic_config("autoresearch"),
|
| 358 |
+
# _agentic_config("meta_harness"),
|
| 359 |
+
],
|
| 360 |
+
max_workers=3,
|
| 361 |
+
**task,
|
| 362 |
+
)
|
| 363 |
+
print(f"\nPhase 1 best score: {explore.best_score:.3f} "
|
| 364 |
+
f"({explore.total_evals} evals)")
|
| 365 |
+
|
| 366 |
+
# -- Phase 2 (continue): seed a fresh run from the winner. --
|
| 367 |
+
print(f"\n=== Phase 2: continue with autoresearch, seeded from the phase-1 "
|
| 368 |
+
f"winner (max_evals={MAX_EVALS}) ===")
|
| 369 |
+
omni = optimize_anything(
|
| 370 |
+
explore.best_candidate,
|
| 371 |
+
config=_agentic_config("autoresearch"),
|
| 372 |
+
**task,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
best = omni if omni.best_score >= explore.best_score else explore
|
| 376 |
+
print(f"\n=== Done. best score: {best.best_score:.3f} ===")
|
| 377 |
+
print("\n--- Optimized answer prompt ---")
|
| 378 |
+
print(coerce_prompt(best.best_candidate))
|
semantic-log-file-mcp.tar.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:934970000fff2250b6b601ee15d9b3cc6b135d65a9b805de9d20d2c6f1280858
|
| 3 |
+
size 61143040
|