Agent skill

Dspy Optimize Anything

by OmidZamani in OmidZamani/dspy-skills

A skill your agent uses for GEPA optimizeanything on text artifacts such as code, prompts, agent architectures, configs, and non-DSPy optimization targets.

MITAuto-check passed

Install Dspy Optimize Anything

skills CLI
$ npx skills add OmidZamani/dspy-skills --skill dspy-optimize-anything -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install OmidZamani/dspy-skills dspy-optimize-anything --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/OmidZamani/dspy-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/dspy-optimize-anything .claude/skills/dspy-optimize-anything && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
dspy-optimize-anything
GitHub stars
123
Token cost
~2.6k tokens
SKILL.md length
464 words
Files
2
Skills in repo
17
Repo updated
First seen
Licence
MIT

At a glance

A skill your agent uses for GEPA optimizeanything on text artifacts such as code, prompts, agent architectures, configs, and non-DSPy optimization targets.

  • Works in 4 steps: Install → Define Evaluator with ASI → Choose Optimization Mode → …
  • GEPA optimizeanything on text artifacts such as code
  • SKILL.md covers Goal, When to Use, Inputs and Outputs, plus 6 more sections
  • Runs Python scripts from its folder; calls pip

What it does

Dspy Optimize Anything is an agent skill from OmidZamani/dspy-skills. Use for GEPA optimizeanything on text artifacts such as code, prompts, agent architectures, configs, and non-DSPy optimization targets.

Its SKILL.md is about 2.6k tokens, which your agent loads only when the skill is triggered. The skill folder holds 1 other file (for example `example.py`).

The repository describes itself as: Collection of Claude Skills for DSPy framework - program language models, optimize prompts, and build RAG pipelines systematically. The licence is MIT.

When your agent uses it

  • GEPA optimizeanything on text artifacts such as code
  • Agent architectures
  • Non-DSPy optimization targets

Example prompts

  • “/dspy-optimize-anything”

Requirements

  • Python 3
  • Pre-approved tools (allowed-tools): Read, Write, Glob, Grep

Workflow steps

4 steps, taken from the step headings in SKILL.md.

  1. Install
  2. Define Evaluator with ASI
  3. Choose Optimization Mode
  4. Use Results

What it can do on your machine

Read from SKILL.md and the folder at commit f5db3b7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Glob
    • Grep

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships script files (Python), which the agent can run.

    Shell commands in SKILL.md call:

    • pip

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • gepa-ai.github.io
    • github.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Dspy Optimize Anything loads about 2.6k tokens when it runs. Until then it costs about 40 tokens; SKILL.md has 464 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~40
When it runs · the whole SKILL.md, loaded when a task matches
~2.6k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from OmidZamani/dspy-skills at commit f5db3b7, republished under its MIT licence (© OmidZamani). 464 words, ~2,567 tokens.

Download SKILL.mdSave it as .claude/skills/dspy-optimize-anything/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
dspy-optimize-anything
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
version
1.0.0
dspy-compatibility
3.2.1
gepa-compatibility
0.1.1
tags
optimizer
requires-extras
gepa>=0.1.1,<0.2

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

InputTypeDescription
seed_candidatestr | dict[str, str] | NoneStarting artifact text, or None for seedless mode
evaluatorCallableReturns score (higher=better), optionally with ASI dict
datasetlist | NoneTraining examples (for multi-task and generalization modes)
valsetlist | NoneValidation set (for generalization mode)
objectivestr | NoneNatural language description of what to optimize for
backgroundstr | NoneDomain knowledge and constraints
configGEPAConfig | NoneEngine, reflection, and tracking settings

Outputs

OutputTypeDescription
result.best_candidatestr | dictBest optimized artifact

Workflow

Phase 1: Install
bash
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):

python
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):

python
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.

python
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.

python
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.

python
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.

python
result = oa.optimize_anything(
    evaluator=evaluate,
    objective="Generate a Python function `reverse()` that reverses a string.",
    config=config,
)
Phase 4: Use Results
python
print(result.best_candidate)

Production Example

python
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}")
        return 0.0, {"Error": proc.stderr}

    try:
        output = json.loads(proc.stdout)
        return output["score"], {
            "Output": output.get("solution"),
            "Runtime": f"{output.get('time_ms', 0):.1f}ms",
        }
    except (json.JSONDecodeError, KeyError) as e:
        oa.log(f"Parse error: {e}")
        return 0.0, {"Error": str(e), "Stdout": proc.stdout}

result = oa.optimize_anything(
    evaluator=evaluate_solver,
    objective="Write a Python solver for the bin packing problem that "
              "minimizes the number of bins. Output JSON with 'score' and 'solution'.",
    background="Use first-fit-decreasing as a starting heuristic. "
               "Higher score = fewer bins used.",
    config=GEPAConfig(engine=EngineConfig(max_metric_calls=100)),
)

print(result.best_candidate)


# ---------- Agent architecture generalization ----------

def evaluate_agent(candidate: str, example: dict) -> tuple[float, dict]:
    """Run an agent architecture on a task and score it."""
    exec_globals = {}
    exec(candidate, exec_globals)
    agent_fn = exec_globals.get("solve")

    if agent_fn is None:
        return 0.0, {"Error": "No `solve` function defined"}

    try:
        prediction = agent_fn(example["input"])
        correct = prediction == example["expected"]
        score = 1.0 if correct else 0.0
        feedback = "Correct" if correct else (
            f"Expected '{example['expected']}', got '{prediction}'"
        )
        return score, {"Prediction": prediction, "Feedback": feedback}
    except Exception as e:
        return 0.0, {"Error": str(e)}

result = oa.optimize_anything(
    seed_candidate="def solve(input):\n    return input",
    evaluator=evaluate_agent,
    dataset=train_tasks,
    valset=val_tasks,
    background="Discover a Python agent function `solve(input)` that "
               "generalizes across unseen reasoning tasks.",
    config=GEPAConfig(engine=EngineConfig(max_metric_calls=100)),
)

print(result.best_candidate)
Show full SKILL.md (188 more words)Show less

Integration with DSPy

optimize_anything complements DSPy's built-in optimizers. Use DSPy optimizers (GEPA, MIPROv2, BootstrapFewShot) for DSPy programs, and optimize_anything for arbitrary text artifacts outside DSPy:

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

# DSPy program optimization (use dspy.GEPA)
optimizer = dspy.GEPA(
    metric=gepa_metric,
    reflection_lm=dspy.LM("openai/gpt-4o"),
    auto="medium",
)
compiled = optimizer.compile(agent, trainset=trainset)

# Non-DSPy artifact optimization (use optimize_anything)
result = oa.optimize_anything(
    seed_candidate=my_config_yaml,
    evaluator=eval_config,
    background="Optimize Kubernetes scheduling policy for cost.",
    config=GEPAConfig(engine=EngineConfig(max_metric_calls=100)),
)

Best Practices

  1. Rich ASI — The more diagnostic feedback you provide, the better the proposer can reason about improvements
  2. Use oa.log() — Route prints to the proposer as ASI instead of stdout
  3. Structured returns — Return (score, dict) tuples for multi-faceted diagnostics
  4. Seedless for exploration — Use objective= when the solution space is large and unfamiliar
  5. Background context — Provide domain knowledge via background= to constrain the search
  6. Generalization mode — Always provide valset when the artifact must transfer to unseen inputs
  7. Images as ASI — Use gepa.Image to pass rendered outputs to vision-capable LLMs
  8. Bound every run — Set GEPAConfig(engine=EngineConfig(max_metric_calls=...))

Limitations

  • Requires the gepa package (pip install -U "gepa>=0.1.1,<0.2")
  • Evaluator must be deterministic or low-variance for stable optimization
  • Compute cost scales with number of candidates explored
  • Single-task mode does not generalize; use mode 3 with valset for transfer
  • Currently powered by GEPA backend; API is backend-agnostic for future strategies

Official Documentation

© OmidZamani, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file in skills/dspy-optimize-anything of OmidZamani/dspy-skills.

  • SKILL.md
  • example.py

Open the folder on GitHubat commit f5db3b7

Compare with similar skills

Dspy Optimize Anything next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Dspy Optimize Anything compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Dspy Optimize Anything this skillOmidZamani/dspy-skills123—~2.6kAutomated safety check: PassMIT
Dspy Gepa Optimizerintertwine/dspy-agent-skills278—~2.6kAutomated safety check: PassMIT
SQL Optimizationgithub/awesome-copilot40k2 repos~2.3kAutomated safety check: PassMIT
Artifacts Buildernexu-io/open-design100k—~347Automated safety check: PassApache-2.0
Agent Performance Optimizerruvnet/ruflo74k2 repos~3.6kAutomated safety check: PassMIT
Database Optimizerdavila7/claude-code-templates33k8 repos~2.5kAutomated safety check: PassMIT

Similar skills

  • Dspy Gepa Optimizer

    intertwine/dspy-agent-skills

    Optimize DSPy programs with dspy.GEPA — a reflective/evolutionary optimizer to consider against task-specific baselines within an authorized evaluation budget.

    278 GitHub stars~2.6k tokensUpdated 1 mo ago
    Auto-check passed
  • SQL Optimization

    github/awesome-copilot

    Official

    Universal SQL performance optimization assistant for comprehensive query tuning, indexing strategies, and database performance analysis across all SQL databases (MySQL, PostgreSQL, SQL Server…

    40k GitHub starsUsed in 2 repos~2.3k tokens
    DatabasesAuto-check passed
  • Artifacts Builder

    nexu-io/open-design

    Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui).

    100k GitHub stars~347 tokensUpdated today
    Frontend & DesignAuto-check passed
  • Agent skill for performance-optimizer - invoke with $agent-performance-optimizer

    74k GitHub starsUsed in 2 repos~3.6k tokens
    Auto-check passed
  • Database Optimizer

    davila7/claude-code-templates

    Expert database optimizer specializing in modern performance tuning, query optimization, and scalable architectures.

    33k GitHub starsUsed in 8 repos~2.5k tokens
    DatabasesAuto-check passed
  • Web Artifacts Builder

    anthropics/skills

    Official

    Builds multi-component claude.ai HTML artifacts as a small React, TypeScript and Tailwind project, then bundles it into one shareable HTML file.

    180k GitHub starsUsed in 40 repos~769 tokens
    Frontend & DesignAuto-check passed

More from OmidZamani/dspy-skills

All 17 skills in this repo
  • Skill Perfection

    OmidZamani/dspy-skills

    A skill your agent uses when you need to QA audit and fix a plugin skill file.

    123 GitHub stars~1.6k tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Haystack Integration

    OmidZamani/dspy-skills

    A skill your agent uses for integrating DSPy with Haystack, optimizing Haystack prompts, improving retrieval pipelines, and extracting DSPy prompts.

    123 GitHub stars~1.4k tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Adapters Multimodal

    OmidZamani/dspy-skills

    A skill your agent uses for DSPy adapter selection, JSONAdapter, XMLAdapter, ChatAdapter, native function calling, structured outputs, and multimodal inputs like dspy.Image or dspy.Audio.

    123 GitHub stars~864 tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Advanced Module Composition

    OmidZamani/dspy-skills

    A skill your agent uses for composing DSPy modules with Ensemble, MultiChainComparison, ensemble voting, sequential pipelines, and multi-program workflows.

    123 GitHub stars~2.2k tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Better Together

    OmidZamani/dspy-skills

    A skill your agent uses for BetterTogether, prompt plus weight optimization, fine-tuning sequences, and strategy chains like p - w - p.

    123 GitHub stars~756 tokensUpdated 3 mo ago
    Auto-check passed
  • Dspy Bootstrap Fewshot

    OmidZamani/dspy-skills

    A skill your agent uses for BootstrapFewShot, bootstrapped demonstrations, teacher-model demos, and low-data DSPy prompt optimization.

    123 GitHub stars~1.3k tokensUpdated 3 mo ago
    Auto-check passed

Questions about Dspy Optimize Anything

What does Dspy Optimize Anything do?

A skill your agent uses for GEPA optimizeanything on text artifacts such as code, prompts, agent architectures, configs, and non-DSPy optimization targets. Dspy Optimize Anything is an agent skill from OmidZamani/dspy-skills. Use for GEPA optimizeanything on text artifacts such as code, prompts, agent architectures, configs, and non-DSPy optimization targets.

When should I use Dspy Optimize Anything?

Dspy Optimize Anything fits situations like: GEPA optimizeanything on text artifacts such as code; agent architectures; non-DSPy optimization targets.

How do I install Dspy Optimize Anything in Claude Code?

Run `npx skills add OmidZamani/dspy-skills --skill dspy-optimize-anything -a claude-code`. Or copy the skill folder (skills/dspy-optimize-anything in OmidZamani/dspy-skills) into .claude/skills/dspy-optimize-anything in your project. Claude Code loads it when a task matches its description.

How do I install Dspy Optimize Anything in Codex?

Run `npx skills add OmidZamani/dspy-skills --skill dspy-optimize-anything -a codex`. Or copy the skill folder (skills/dspy-optimize-anything in OmidZamani/dspy-skills) into .agents/skills/dspy-optimize-anything in your project. Codex loads it when a task matches its description.

Can I use Dspy Optimize Anything in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add OmidZamani/dspy-skills --skill dspy-optimize-anything -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/dspy-optimize-anything, .gemini/skills/dspy-optimize-anything, .github/skills/dspy-optimize-anything and .opencode/skills/dspy-optimize-anything in your project.

What does Dspy Optimize Anything need to run?

Going by SKILL.md and its folder, Dspy Optimize Anything needs Python for the scripts in its folder and the command-line tools its instructions call (pip). Our summary lists: Python 3. Its frontmatter pre-approves these tools: Read, Write, Glob, Grep.

Does Dspy Optimize Anything access the network?

SKILL.md names 2 domains. As links in the text: gepa-ai.github.io and github.com. This is read from the text; nothing was executed.

Is Dspy Optimize Anything safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Dspy Optimize Anything use?

Dspy Optimize Anything is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Dspy Optimize Anything use?

About 2.6k tokens (SKILL.md is roughly 10k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Dspy Optimize Anything?

Skills that share tags, products or a category with Dspy Optimize Anything: Dspy Gepa Optimizer (intertwine/dspy-agent-skills, 278 stars), SQL Optimization (github/awesome-copilot, 40k stars), Artifacts Builder (nexu-io/open-design, 100k stars) and Agent Performance Optimizer (ruvnet/ruflo, 74k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Dspy Optimize Anything?

OmidZamani (a GitHub user) maintains it in OmidZamani/dspy-skills, which has 123 GitHub stars. The repository holds 17 skills in this directory. The repository was last updated on June 23, 2026.

Source: OmidZamani/dspy-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.