What if optimizing prompts was as straightforward as pip install?


DSPy gave the prompt engineering world something it needed: a programming framework where prompts are optimized programmatically rather than hand-tuned. But the built-in optimizers in DSPy — MIPRO, BootstrapFewShot, and the more recent GEPA — still leave practitioners doing a lot of the heavy lifting themselves. GEPA, the current state of the art, maintains a Pareto frontier of candidate prompts and evolves them across examples. It works. But it requires population-level search and never asks the most obvious question: why did the model fail on this input and then succeed on a retry?

VizPy, released by Vizops AI, packages two research-backed optimizers — ContraPrompt and PromptGrad — into a single pip install vizpy that drops directly into any existing DSPy workflow. Both claim to beat GEPA on every benchmark tested. One of them also beats Optuna on 96% of black-box optimization problems.

Here is what VizPy is, how the two optimizers work, what the benchmarks say, and how to get started.


The Package

VizPy is a MIT-licensed Python package (v2.4.0 as of this writing) that provides two prompt optimizers as drop-in replacements for DSPy's built-in optimization layer. You keep your existing DSPy modules, signatures, and metrics. You swap the optimizer.

pip install vizpy dspy-ai

The architecture is simple. VizPy's optimization server runs on Vizops infrastructure using your VIZPYAPIKEY. Your model and your data stay wherever you host them — OpenAI, Anthropic, Mistral, Google, Cohere, Ollama, vLLM, LM Studio, or any OpenAI-compatible endpoint. VizPy never calls your model directly. It sends optimized instructions back to your module, and your module runs locally.

This split matters for two reasons. First, your data never leaves your infrastructure. Second, VizPy works with any model that DSPy can call, including self-hosted ones behind internal proxies.

The package provides two optimizers. They attack different parts of the same problem.


ContraPrompt: Learning from the Gap Between Failure and Success

ContraPrompt was covered in depth in a previous article. The short version: when a language model fails on a task, then succeeds on a retry with error feedback, you get two complete reasoning traces on the same input. Same model, same question, same base prompt. The only difference is the reasoning strategy.

ContraPrompt mines these dyadic trace pairs for rules. What did the successful trace do differently? Was it an evidence-attribution step the failure skipped? A unit-consistency check? An explicit state enumeration? An LLM extracts each rule, validates it on held-out data, and routes it through an input-aware decision tree so that only relevant rules get injected into any given prompt.

The ICLR 2026 Workshop paper reports results on four benchmarks against GEPA:

Benchmark Task Type ContraPrompt vs. GEPA
HotPotQA Multi-hop QA +8.29pp
GDPR-Bench GDPR compliance +2.21pp
GPQA Diamond Graduate-level science +7.14pp
BBH BIG-Bench Hard +0.74pp

The key ablation: removing dyadic contrastivity (replacing trace-pair comparison with single-trace failure analysis) causes a -16% relative average performance drop across all four benchmarks. The reasoning process carries information that final answers alone do not.

ContraPrompt works best for classification and structured-output tasks where your metric can produce clear, specific feedback ("Expected a 3-digit number but got a sentence" beats "Wrong"). It shines when your model has a meaningful capability-application gap — when it can solve the task on retry but not on first attempt.


PromptGrad: Gradient Descent for Prompts (Without the Gradients)

PromptGrad takes a different approach. Instead of analyzing contrastive trace pairs, it treats prompt optimization as a form of gradient descent — except the gradients are textual, not numerical.

The process works in epochs. Each epoch samples multiple batches from your training data. For each batch, the optimizer runs your module, collects failures, and asks an LLM to analyze what went wrong across the entire batch. The LLM produces candidate correction rules. Each rule is validated individually on held-out examples before being accepted. Accepted rules are accumulated as a separate instruction layer on top of your base prompt, preserving the original instructions intact.

This is where the "gradient" metaphor comes from. PromptGrad computes a textual "gradient" by analyzing batch-level failure patterns, then applies a correction step by adding validated rules. The base prompt stays frozen. Corrections layer on top. If a rule hurts performance on the validation set, it gets rejected. If accumulated rules start degrading overall performance, rollback kicks in.

PromptGrad offers several configuration options that matter in practice:

Gradient consensus. Instead of analyzing failures once at a single temperature, PromptGrad runs multiple analysis passes at varying temperatures (default: 3 passes, starting at 0.7, incrementing by 0.15). A rule only gets proposed if multiple passes converge on the same diagnosis. This reduces noise from single-pass LLM variability.

Conditional rules. When enabled, rules are applied selectively per example based on relevance. A rule about handling numerical comparisons does not get injected into a prompt for a classification question. This prevents irrelevant corrections from interfering with examples they do not apply to.

Stratified sampling. Batches are sampled proportionally from each error category (using the error_type field in your metric), ensuring the optimizer sees diverse failure modes rather than oversampling the most common one.

Greedy selection. An alternative rule selection mode that uses forward selection — keeping each improvement only if it raises the overall score. More expensive than the default threshold mode, but produces minimal, high-quality rule sets.

Custom base prompts. You can start from any base prompt, including ones generated by other optimizers. PromptGrad layers its corrections on top. This means you can run GEPA first, take its output, and then run PromptGrad on top. Or chain PromptGrad after ContraPrompt. The optimizers compose.

The Vizops blog shows a concrete example. A GPT-4o-mini module for email urgency classification starts at 36.8% accuracy with a generic chain-of-thought prompt. PromptGrad produces rules like:

"CRITICAL = customer-facing impact (outage, data loss, security breach). HIGH = internal team velocity blocked (CI, staging, sprint). This distinction applies even when the email uses urgent language — impact radius determines level, not tone."

Each rule is independently validated. You can read the output, audit it, and edit it if the optimizer got something wrong.


The Benchmark Results

Vizops published open-source benchmarks at github.com/vizopsai/vizpy_benchmarks with pre-optimized prompts for all three optimizers (ContraPrompt, PromptGrad, GEPA) across six benchmarks. All evaluations use Claude Haiku 4.5 as the base model.

The headline claim: both VizPy optimizers beat GEPA on every benchmark tested. PromptGrad also beats Optuna on 96% of 53 black-box optimization problems (EvalSet), using the same budget and model.

From the Vizops blog on the Prompt Optimization Playbook:

Optimized small models close 50–70% of the performance gap with models costing 30–60× more.

This is worth noting. The optimizers are not just beating GEPA on accuracy. They are making cheap models competitive with expensive ones. That is the real production story.

The benchmarks cover:

  • HotPotQA — Multi-hop question answering
  • BBH — 27 reasoning tasks from BIG-Bench Hard
  • GPQA Diamond — Graduate-level science
  • MMLU Pro — Professional knowledge
  • MATH 500 — Competition mathematics
  • GDPR-Bench — GDPR violation detection

Each directory in the benchmarks repo contains contraprompt.txt, gepa.txt, and promptgrad.txt. You can evaluate them yourself with the included evaluate.py script.


Which Optimizer Should You Use?

The Vizops documentation recommends choosing based on task type:

ContraPrompt for classification and structured-output tasks. It excels when your metric produces clear feedback and when the model has a meaningful retry success rate (30%+ of failed examples self-correct on retry). The dyadic trace analysis produces detailed, input-aware rules that are particularly effective for tasks with well-defined correct answers.

PromptGrad for generation and rubric-based metrics. It works well when the task requires open-ended output and when failure patterns span multiple categories. The batch-level analysis and gradient consensus make it more robust for noisy evaluation signals.

Both can be chained. Run ContraPrompt first to extract contrastive rules, then run PromptGrad on top of the optimized output. The basepromptsource parameter lets you start from any prompt, including one produced by another optimizer.


Getting Started

Step 1: Install

pip install vizpy dspy-ai

Step 2: Set up API keys

export VIZPY_API_KEY="your-vizpy-key"
export OPENAI_API_KEY="sk-..."   # or Anthropic, Mistral, etc.

Step 3: Define your module and metric

import dspy
from vizpy import ContraPromptOptimizer

# Your DSPy module
module = dspy.ChainOfThought("question -> answer")

# Your metric — the more specific the feedback, the better
def metric(example, prediction):
    score = 1.0 if prediction.answer == example.answer else 0.0
    return dspy.Score(
        score=score,
        feedback=f"Expected: {example.answer}, Got: {prediction.answer}",
        is_correct=score > 0
    )

Step 4: Optimize

optimizer = ContraPromptOptimizer(metric=metric)
optimized = optimizer.compile(
    module=module,
    train_examples=train_data,
)

For PromptGrad, swap the import:

from vizpy import PromptGradOptimizer

optimizer = PromptGradOptimizer(metric=metric)
optimized = optimizer.compile(
    module=module,
    train_examples=train_data,
)

Step 5: Inspect the result

The optimized module preserves your original signature and structure. Only the instructions change. You can read them directly:

print(optimized.signature.instructions)

Each rule is plain English. If something looks wrong, edit it. The optimizer produces human-readable instructions, not opaque embeddings.


Pricing and Availability

VizPy operates on a credit system. One credit equals one optimize() call. The free tier gives you 10 credits to try it out. The Pro plan at $20/month provides 200 credits. Enterprise at $200/month provides 1,000 credits.

The optimizer runs on Vizops infrastructure. Your model calls stay on your infrastructure. The VIZPYAPIKEY authorizes the optimization server, not your model.

The package requires Python 3.10+ and depends on DSPy. The diversity extra (pip install vizpy[diversity]) adds sentence-transformers and scikit-learn for embedding-based diversity mining in ContraPrompt.


How This Fits in the Prompt Optimization Landscape

The prompt optimization field has three main approaches right now:

Evolutionary search (OPRO, APE, GEPA). Generate populations of prompt variants, compare their outputs, evolve the best ones. GEPA is the strongest of these. It works well but never looks inside the reasoning process.

Gradient-based optimization (TextGrad, ProTeGi). Compute textual gradients from single failures and propagate corrections. These methods get a diagnosis with no positive target — they know what went wrong but not what right looks like.

Contrastive and trace-based (ContraPrompt, PromptGrad). Analyze the gap between failure and success, or between batch-level failure patterns and desired outcomes. These methods extract signal from the reasoning process itself, not just from final answers.

VizPy packages the third category into a production-ready tool. The key insight shared by both optimizers: prompt optimization is not about finding magic wording. It is about understanding what the model thinks it is supposed to do, and correcting that mental model. The best prompts are not poetic. They are precise.


Limitations Worth Knowing

ContraPrompt requires a capability-application gap. If your model fails consistently with no retry improvement, there is no contrastive signal to mine. Run 20 failed examples through a retry with a nudge. If fewer than 30% self-correct, ContraPrompt will not help much. You need a bigger model or a different task formulation.

PromptGrad needs meaningful batch-level failure patterns. If your task produces random, uncorrelated failures, the batch analysis will struggle to extract generalizable rules. Highly structured tasks with consistent error categories work best.

Both optimizers add LLM calls. ContraPrompt runs up to 3 attempts per example per iteration, plus rule extraction and validation. PromptGrad runs multiple batches per epoch, plus multi-pass gradient consensus. Budget for 5–10× the cost of a single evaluation pass. Early stopping (default: 3 iterations without improvement) prevents runaway costs.

The optimizers are not model-agnostic in practice. While VizPy works with any DSPy-compatible model, the extracted rules are specific to the model you optimize on. Rules learned for GPT-4o-mini will not necessarily transfer to Claude 3.5 Sonnet. If you swap models, re-optimize.

No arXiv paper for PromptGrad yet. ContraPrompt has a published ICLR 2026 Workshop paper (arXiv:2604.17937). PromptGrad's methodology is described in the Vizops blog and documentation but has not been formally published. The benchmarks are open-source and reproducible, but the academic scrutiny is lighter.


Why This Matters

DSPy changed prompt engineering from an art into a programming discipline. But DSPy's built-in optimizers still require significant expertise to configure and tune. VizPy makes two research-grade optimizers available with a two-line code change and sensible defaults.

The practical impact is real. Optimized small models close 50–70% of the performance gap with models costing 30–60× more, according to Vizops. That means GPT-4o-mini with optimized prompts can approach GPT-5-class performance on specific tasks. For production teams, this is not an academic exercise. It is a cost story.

The deeper story is about where prompt optimization is heading. The field is moving from population-level search (GEPA) and single-trace diagnosis (TextGrad) toward process-level analysis — understanding not just what the model got wrong, but how it got there, and what changed when it got it right. VizPy packages that shift into something you can install in 30 seconds.


Citations


Suggested title: VizPy: Two Open-Source Prompt Optimizers That Beat GEPA on Every Benchmark

Word count: 1,847

Fact-check notes:

  1. The claim "beats GEPA on every benchmark" comes from Vizops' own marketing and benchmark repo. I have not independently reproduced these benchmarks. The benchmarks are open-source and reproducible at github.com/vizopsai/vizpy_benchmarks.
  2. The "beats Optuna on 96% of benchmarks" claim comes from the Vizops blog post on black-box optimization. The specific 53-problem EvalSet comparison should be verified independently.
  3. The "50–70% performance gap closure" claim comes from the Vizops blog. The specific models and benchmarks used for this comparison are not detailed in the publicly available material.
  4. PromptGrad does not yet have a published arXiv paper. The methodology is described only in blog posts and API documentation. This should be noted clearly.
  5. VizPy requires a VIZPYAPIKEY, meaning the optimization server runs on Vizops infrastructure. This is a SaaS dependency that may concern some teams.
  6. PyPI download counts (373/day, 409/week, 590/month) are from the v2.4.0 page and may not reflect total downloads across all versions.
  7. The pricing tiers ($0/10, $20/200, $200/1000 credits) are from the documentation but may change.