data / optanything_rag_claudecode (1).py
infinex's picture
Uploading dataset files from the local data folder.
b381f1c verified
Raw
History Blame Contribute Delete
16.8 kB
"""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_TRAINSET,
valset=RAG_VALSET,
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))