Skip to content
Development
Skill

/dspy-optimize-anything

Use for GEPA optimize_anything on text artifacts such as code, prompts, agent architectures, configs, and non-DSPy optimization targets.

From plugin
dspy-skills
12323 skills
Install
$ npx -y skills add OmidZamani/dspy-skills --skill dspy-optimize-anything --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/dspy-optimize-anything

Context preview

The summary Claude sees to decide when to auto-load this skill.

Use for GEPA optimize_anything on text artifacts such as code, prompts, agent architectures, configs, and non-DSPy optimization targets.

SKILL.md

dspy-optimize-anything.SKILL.md
name: dspy-optimize-anything
version: "1.0.0"
dspy-compatibility: "3.2.1"
gepa-compatibility: "0.1.1"
tags: ["optimizer"]
requires-extras: ["gepa>=0.1.1,<0.2"]
description: Use for GEPA optimize_anything on text artifacts such as code, prompts, agent architectures, configs, and non-DSPy optimization targets.
allowed-tools:
  - Read
  - Write
  - Glob
  - Grep

GEPA optimize_anything

Goal

Optimize any artifact representable as text — code, prompts, agent architectures, vector graphics, configurations — using a single declarative API powered by GEPA's reflective evolutionary search.

When to Use

  • **Beyond prompt optimization** — optimizing code, configs, SVGs, scheduling policies, etc.
  • **Single hard problems** — circle packing, kernel generation, algorithm discovery
  • **Batch related problems** — CUDA kernels, code generation tasks with cross-transfer
  • **Generalization** — agent skills, policies, or prompts that must transfer to unseen inputs
  • When you can **express quality as a score** and provide **diagnostic feedback** (ASI)

Inputs

| Input | Type | Description | |-------|------|-------------| | `seed_candidate` | `str \| dict[str, str] \| None` | Starting artifact text, or `None` for seedless mode | | `evaluator` | `Callable` | Returns score (higher=better), optionally with ASI dict | | `dataset` | `list \| None` | Training examples (for multi-task and generalization modes) | | `valset` | `list \| None` | Validation set (for generalization mode) | | `objective` | `str \| None` | Natural language description of what to optimize for | | `background` | `str \| None` | Domain knowledge and constraints | | `config` | `GEPAConfig \| None` | Engine, reflection, and tracking settings |

Outputs

| Output | Type | Description | |--------|------|-------------| | `result.best_candidate` | `str \| dict` | Best optimized artifact |

Workflow

Phase 1: Install

pip install -U "gepa>=0.1.1,<0.2"

Phase 2: Define Evaluator with ASI

The evaluator scores a candidate and returns Actionable Side Information (ASI) — diagnostic feedback that guides the LLM proposer during reflection.

**Simple evaluator (score only):**

import gepa.optimize_anything as oa
from gepa.optimize_anything import EngineConfig, GEPAConfig

config = GEPAConfig(engine=EngineConfig(max_metric_calls=100))

def evaluate(candidate: str) -> float:
    score, diagnostic = run_my_system(candidate)
    oa.log(f"Error: {diagnostic}")  # captured as ASI
    return score

**Rich evaluator (score + structured ASI):**

def evaluate(candidate: str) -> tuple[float, dict]:
    result = execute_code(candidate)
    return result.score, {
        "Error": result.stderr,
        "Output": result.stdout,
        "Runtime": f"{result.time_ms:.1f}ms",
    }

ASI can include open-ended text, structured data, multi-objectives (via `scores`), or images (via `gepa.Image`) for vision-capable LLMs.

Phase 3: Choose Optimization Mode

**Mode 1 — Single-Task Search:** Solve one hard problem. No dataset needed.

result = oa.optimize_anything(
    seed_candidate="<your initial artifact>",
    evaluator=evaluate,
    config=config,
)

**Mode 2 — Multi-Task Search:** Solve a batch of related problems with cross-transfer.

result = oa.optimize_anything(
    seed_candidate="<your initial artifact>",
    evaluator=evaluate,
    dataset=tasks,
    config=config,
)

**Mode 3 — Generalization:** Build a skill/prompt/policy that transfers to unseen problems.

result = oa.optimize_anything(
    seed_candidate="<your initial artifact>",
    evaluator=evaluate,
    dataset=train,
    valset=val,
    config=config,
)

**Seedless mode:** Describe what you need instead of providing a seed.

result = oa.optimize_anything(
    evaluator=evaluate,
    objective="Generate a Python function `reverse()` that reverses a string.",
    config=config,
)

Phase 4: Use Results

print(result.best_candidate)

Production Example

import gepa.optimize_anything as oa
from gepa import Image
from gepa.optimize_anything import EngineConfig, GEPAConfig
import logging

logger = logging.getLogger(__name__)

# ---------- SVG optimization with VLM feedback ----------

GOAL = "a pelican riding a bicycle"
VLM = "vertex_ai/gemini-3-flash-preview"

VISUAL_ASPECTS = [
    {"id": "overall",     "criteria": f"Rate overall quality of this SVG ({GOAL}). SCORE: X/10"},
    {"id": "anatomy",     "criteria": "Rate pelican accuracy: beak, pouch, plumage. SCORE: X/10"},
    {"id": "bicycle",     "criteria": "Rate bicycle: wheels, frame, handlebars, pedals. SCORE: X/10"},
    {"id": "composition", "criteria": "Rate how convincingly the pelican rides the bicycle. SCORE: X/10"},
]

def evaluate(candidate, example):
    """Render SVG, score with a VLM, return (score, ASI)."""
    image = render_image(candidate["svg_code"])  # via cairosvg
    score, feedback = get_vlm_score_feedback(VLM, image, example["criteria"])

    return score, {
        "RenderedSVG": Image(base64_data=image, media_type="image/png"),
        "Feedback": feedback,
    }

result = oa.optimize_anything(
    seed_candidate={"svg_code": "<svg>...</svg>"},
    evaluator=evaluate,
    dataset=VISUAL_ASPECTS,
    background=f"Optimize SVG source code depicting '{GOAL}'. "
               "Improve anatomy, composition, and visual quality.",
    config=GEPAConfig(engine=EngineConfig(max_metric_calls=100)),
)

logger.info(f"Best SVG:\n{result.best_candidate['svg_code']}")


# ---------- Code optimization (single-task) ----------

def evaluate_solver(candidate: str) -> tuple[float, dict]:
    """Evaluate a Python solver for a mathematical optimization problem."""
    import subprocess, json

    proc = subprocess.run(
        ["python", "-c", candidate],
        capture_output=True, text=True, timeout=30,
    )

    if proc.returncode != 0:
        oa.log(f"Runtime error: {proc.stderr}")
Read more
Ships withdspy-skills

A Claude Code plugin containing 22 focused skills for programming, optimizing, evaluating, and deploying LLM applications with DSPy. Stable DSPy baseline: 3.2.1, released May 5, 2026.

Get the whole plugin
Stats
123
Stars
13
Forks
Maintained
Maintenance
Python
Language
MIT
License
2mo ago
Last commit
9mo ago
Created

Repo: OmidZamani/dspy-skills

Other skills on dspy-skills.