| """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 |
|
|
| |
| |
| MAX_EVALS = int(os.environ.get("GEPA_MAX_EVALS", "20")) |
| |
| |
| CLAUDE_MODEL = os.environ.get("GEPA_CLAUDE_MODEL", "sonnet") |
| CLAUDE_TIMEOUT = int(os.environ.get("GEPA_CLAUDE_TIMEOUT", "600")) |
| |
| SANDBOX = os.environ.get("GEPA_SANDBOX", "1") not in ("0", "false", "no", "") |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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", |
| |
| "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." |
| ), |
| }, |
| ] |
|
|
| |
| |
| |
| |
| |
| 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", |
| |
| "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." |
| ), |
| }, |
| ] |
|
|
|
|
| |
| |
| |
| |
| 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) |
| |
| 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)) |
|
|
|
|
| |
| |
| |
| |
| |
| _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() |
|
|
|
|
| |
| |
| |
| 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 |
|
|
|
|
| |
| |
| |
| |
| |
| |
| 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, { |
| |
| |
| "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." |
| ) |
|
|
| |
| |
| 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, |
| ) |
|
|
| |
| |
| |
| print(f"\n=== Phase 1: explore (autoresearch only, " |
| f"max_evals={MAX_EVALS}, sandbox={SANDBOX}) ===") |
| explore = optimize_best_of( |
| SEED_PROMPT, |
| configs=[ |
| |
| _agentic_config("autoresearch"), |
| |
| ], |
| max_workers=3, |
| **task, |
| ) |
| print(f"\nPhase 1 best score: {explore.best_score:.3f} " |
| f"({explore.total_evals} evals)") |
|
|
| |
| 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)) |
|
|