File size: 16,760 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
"""optimize_anything "omni" + Claude Code β€” RAG *answer-prompt* optimization.

A sibling of ``optanything_claudecode.py``. Same two-phase **omni-GEPA** pattern
(https://gepa-ai.github.io/gepa/blog/2026/07/22/optimize-anything-omni/), but the
task is prompt engineering for a **retrieval-augmented QA** system instead of
SVG drawing.

The key framing the user asked for: **the query and the retrieved content are
FIXED β€” retrieval is frozen. The ONLY thing being optimized is the prompt used
to answer the question.**

  * The optimized artifact (the "candidate") is a single ANSWER-GENERATION
    PROMPT β€” the instruction block that tells the model how to use the retrieved
    context to answer. GEPA rewrites this string; nothing else moves.
  * Each dataset row is a frozen (question, context, gold_answer) triple. The
    context is a pre-retrieved bundle of passages that deliberately includes
    distractors, and one row whose answer is *absent* from the context (so a
    good prompt must abstain rather than hallucinate).

  * PHASE 1 (explore) β€” ``optimize_best_of`` runs three engines in parallel and
    keeps the single best answer-prompt:
        - ``gepa``         : reflective evolution; its reflection LM is the
                             `claude` CLI (it reads each generated answer + the
                             judge's critique).
        - ``autoresearch`` : a black-box research optimizer that spawns
                             ``claude --print`` to iterate on the prompt.
        - ``meta_harness`` : an iterative meta-optimizer, also Claude-driven.
  * PHASE 2 (continue) β€” a fresh 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: take the candidate prompt,
splice in the FIXED context + question, ask Claude Code to answer *grounded in
that context only*, then ask Claude Code to grade the answer against the gold
answer and parse ``SCORE: X/10``. The score + textual feedback (Actionable Side
Information) flows back to whichever engine asked for it.

Prereqs (identical to optanything_claudecode.py):
  * `claude` CLI on PATH and authenticated (`claude -p "hi"` works).
  * `bwrap` on PATH if GEPA_SANDBOX=1 (the default).
  * gepa installed from git main (the "omni" API is unreleased as of 0.1.4);
    see pyproject.toml.

Run:  uv run python optanything_rag_claudecode.py
"""

import os
import re
import subprocess

from gepa.optimize_anything import (
    optimize_anything,
    optimize_best_of,
    OptimizeAnythingConfig,
)
from gepa.gepa_launcher import GEPAConfig, EngineConfig, ReflectionConfig

# Per-engine eval-server budget. Phase 1 spends this on EACH of the three
# engines (they run concurrently), phase 2 spends it once more.
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", "")


# ---------------------------------------------------------------------------
# The FROZEN RAG corpus + queries.
#
# In a real system these `context` strings come out of a retriever. Here they
# are pre-retrieved and hard-coded: retrieval is FIXED, so the optimizer can
# only improve how the model *reads* the context to answer β€” never what gets
# retrieved. The passages include distractors, and `nyquist` has NO supporting
# passage on purpose (its gold answer is an explicit "not in context" abstain).
#
# The corpus is split TRAIN / VAL. GEPA optimizes the prompt against the
# trainset and scores candidates on the held-out valset to pick the one that
# GENERALIZES β€” the winning prompt must work on questions/contexts it never
# trained on, not just overfit the training rows. The valset mirrors the same
# stresses (a distractor row + an abstain-required row) over UNSEEN content.
# ---------------------------------------------------------------------------
RAG_TRAINSET = [
    {
        "id": "capital",
        "question": "What is the capital city mentioned for the Kingdom of Aldoria?",
        "context": (
            "[Doc 12] Aldoria is a mountainous kingdom. Its largest port is Vellmar.\n"
            "[Doc 47] The seat of Aldorian government and its capital is the walled "
            "city of Threnhold, founded 800 years ago.\n"
            "[Doc 51] Neighbouring Corvane has its capital at Ashgate."
        ),
        "gold_answer": "Threnhold.",
    },
    {
        "id": "multi_hop",
        "question": "Who succeeded the ruler who commissioned the Great Aqueduct?",
        "context": (
            "[Doc 03] The Great Aqueduct was commissioned by Queen Maeve during her reign.\n"
            "[Doc 09] Queen Maeve reigned for 31 years and was succeeded by her nephew, King Doran.\n"
            "[Doc 22] King Doran later abdicated in favour of a council."
        ),
        "gold_answer": "King Doran (Queen Maeve's nephew) succeeded her.",
    },
    {
        "id": "number",
        "question": "How long did the siege of Threnhold last?",
        "context": (
            "[Doc 31] The siege of Threnhold began in spring and, after repeated assaults, "
            "the walls held for exactly 214 days before the attackers withdrew.\n"
            "[Doc 32] Threnhold's walls are 12 metres high."
        ),
        "gold_answer": "214 days.",
    },
    {
        "id": "distractor",
        "question": "What is Aldoria's chief export?",
        "context": (
            "[Doc 15] Aldoria is famous for its silver mines; refined silver is its chief export.\n"
            "[Doc 16] Corvane, by contrast, exports mostly timber.\n"
            "[Doc 17] Aldorian cuisine features salted fish from Vellmar."
        ),
        "gold_answer": "Silver (refined silver).",
    },
    {
        "id": "nyquist",
        # No passage supports this β€” a good answer prompt must ABSTAIN, not guess.
        "question": "What is the population of Threnhold?",
        "context": (
            "[Doc 47] The seat of Aldorian government and its capital is the walled "
            "city of Threnhold, founded 800 years ago.\n"
            "[Doc 32] Threnhold's walls are 12 metres high."
        ),
        "gold_answer": (
            "The population is not stated in the provided context; a correct answer "
            "must say the information is not available rather than guess a number."
        ),
    },
]

# Held-out validation set β€” UNSEEN questions over UNSEEN content. GEPA never
# optimizes against these; they are used only to score candidates for
# generalization, so the winning prompt is the one that transfers, not the one
# that memorised the trainset. Same stress mix: a distractor row (`val_export`)
# and an abstain-required row (`val_abstain`).
RAG_VALSET = [
    {
        "id": "val_capital",
        "question": "Which city is the capital of Corvane?",
        "context": (
            "[Doc 51] Neighbouring Corvane has its capital at Ashgate.\n"
            "[Doc 63] Corvane's largest festival is held each autumn in the town of Brill.\n"
            "[Doc 64] Ashgate sits at the mouth of the River Corve."
        ),
        "gold_answer": "Ashgate.",
    },
    {
        "id": "val_number",
        "question": "How many towers does Ashgate castle have?",
        "context": (
            "[Doc 70] Ashgate castle is ringed by a moat and defended by nine towers.\n"
            "[Doc 71] The castle's great hall seats three hundred."
        ),
        "gold_answer": "Nine towers.",
    },
    {
        "id": "val_export",
        "question": "What does Corvane mainly export?",
        "context": (
            "[Doc 16] Corvane exports mostly timber from its northern forests.\n"
            "[Doc 15] Aldoria, by contrast, is famous for silver.\n"
            "[Doc 17] Corvane also brews a well-known cider."
        ),
        "gold_answer": "Timber.",
    },
    {
        "id": "val_abstain",
        # No passage gives the founding year β€” the prompt must ABSTAIN.
        "question": "In what year was Ashgate castle built?",
        "context": (
            "[Doc 70] Ashgate castle is ringed by a moat and defended by nine towers.\n"
            "[Doc 64] Ashgate sits at the mouth of the River Corve."
        ),
        "gold_answer": (
            "The founding year is not stated in the provided context; a correct "
            "answer must say the information is not available rather than guess."
        ),
    },
]


# ---------------------------------------------------------------------------
# Claude Code CLI helper (shared by the answerer, the judge, and β€” for the
# `gepa` engine β€” the reflection LM).
# ---------------------------------------------------------------------------
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 claude_reflection_lm(prompt):
    """Reflection LM backed by the `claude` CLI (text-only for this task)."""
    if isinstance(prompt, str):
        return _claude_cli(prompt)
    # Flatten any chat-messages form to plain text (no images here).
    parts: list[str] = []
    for msg in prompt:
        content = msg.get("content", "")
        if isinstance(content, str):
            parts.append(content)
        else:
            for part in content:
                if part.get("type") == "text":
                    parts.append(part.get("text", ""))
    return _claude_cli("\n\n".join(p for p in parts if p))


# ---------------------------------------------------------------------------
# The candidate is a plain-text answer prompt. The agentic engines return
# whatever `claude` wrote β€” sometimes wrapped in ``` fences or prefaced with
# prose ("Here is the improved prompt:"). Strip fences; otherwise use as-is.
# ---------------------------------------------------------------------------
_FENCE_RE = re.compile(r"^```[a-zA-Z]*\n(.*?)\n```", re.DOTALL | re.MULTILINE)


def coerce_prompt(candidate: str) -> str:
    """Pull the answer prompt out of a candidate string."""
    m = _FENCE_RE.search(candidate)
    return (m.group(1) if m else candidate).strip()


# ---------------------------------------------------------------------------
# Answer generation + grading, both via Claude Code.
# ---------------------------------------------------------------------------
def generate_answer(answer_prompt: str, question: str, context: str) -> str:
    """Run the candidate answer-prompt against the FIXED context + question."""
    full = (
        f"{answer_prompt}\n\n"
        f"=== RETRIEVED CONTEXT (do not use outside knowledge) ===\n{context}\n\n"
        f"=== QUESTION ===\n{question}\n\n"
        f"=== ANSWER ==="
    )
    return _claude_cli(full).strip()


def grade_answer(question: str, gold: str, answer: str) -> tuple[float, str]:
    """LLM-judge the generated answer against the gold answer -> (0..1, text)."""
    prompt = (
        "You are grading a retrieval-augmented QA system's answer.\n\n"
        f"QUESTION:\n{question}\n\n"
        f"REFERENCE (gold) ANSWER:\n{gold}\n\n"
        f"SYSTEM ANSWER:\n{answer}\n\n"
        "Grade the system answer for factual correctness and grounding relative "
        "to the reference. Full marks require the right fact (or a correct "
        "abstention when the reference says the info is unavailable), concisely "
        "stated and grounded in the context. Penalise hallucinations, hedging, "
        "and answering when the reference says to abstain.\n"
        "Give one or two sentences of concrete, actionable feedback on how the "
        "ANSWER PROMPT could be rewritten to fix what went wrong, then end with a "
        "line exactly of the form 'SCORE: X/10'."
    )
    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


# ---------------------------------------------------------------------------
# Task definition β€” ONE evaluator, shared by every engine.
#
# `candidate` is the answer-generation prompt string. `example` is one frozen
# (question, context, gold_answer) row.
# ---------------------------------------------------------------------------
def evaluate(candidate, example):
    """Answer the FIXED query with the candidate prompt, then grade it."""
    answer_prompt = coerce_prompt(candidate)
    try:
        answer = generate_answer(answer_prompt, example["question"], example["context"])
    except Exception as e:
        return 0.0, {"Feedback": f"Answer generation failed ({type(e).__name__}): {e}"}
    score, feedback = grade_answer(example["question"], example["gold_answer"], answer)
    return score, {
        # The generated answer is the actionable side-info the reflection LM
        # reads to understand *why* this prompt scored what it did.
        "GeneratedAnswer": answer,
        "Feedback": feedback,
    }


OBJECTIVE = (
    "Optimize the ANSWER PROMPT for a retrieval-augmented QA system. Retrieval "
    "is fixed; only the prompt that instructs the model how to answer from the "
    "retrieved context may change. Output ONLY the prompt text."
)
BACKGROUND = (
    "The candidate is a reusable ANSWER PROMPT. At eval time it is concatenated "
    "with a FROZEN retrieved-context bundle and a question, and a model produces "
    "an answer strictly from that context. A judge grades the answer 0-10 "
    "against a gold reference for factual correctness and grounding. The corpus "
    "contains distractor passages and at least one question whose answer is NOT "
    "in the context β€” for that one a correct answer must ABSTAIN ('not stated in "
    "the context') rather than hallucinate. A good prompt therefore enforces: "
    "answer only from the context, cite/quote support, be concise, and abstain "
    "when the context lacks the answer. Output ONLY the prompt text."
)

# A deliberately weak seed prompt β€” it neither grounds nor abstains, so there is
# room for the optimizer to improve it.
SEED_PROMPT = "Answer the question."


def _gepa_config() -> OptimizeAnythingConfig:
    """Reflective-evolution engine, with Claude Code as its reflection LM."""
    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__":
    task = dict(
        evaluator=evaluate,
        dataset=RAG_DATASET,
        objective=OBJECTIVE,
        background=BACKGROUND,
    )

    # -- Phase 1 (explore): run engines in parallel, keep the best prompt. --
    # Mirroring optanything_claudecode.py, only the autoresearch engine is
    # enabled by default; uncomment the others to run the full best-of-three.
    print(f"\n=== Phase 1: explore (autoresearch only, "
          f"max_evals={MAX_EVALS}, sandbox={SANDBOX}) ===")
    explore = optimize_best_of(
        SEED_PROMPT,
        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 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("\n--- Optimized answer prompt ---")
    print(coerce_prompt(best.best_candidate))