An algorithm once beat the most famous human-written reasoning prompt; DSPy applies this kind of search to the entire pipeline, so switching models no longer requires manual retuning.

Key takeaways

  • The APE paper showed that on 19 of 24 NLP tasks, LLM-generated instructions matched or exceeded those written by human annotators.
  • DSPy treats prompts as parameters: its compiler optimizes the entire pipeline to maximize a metric you specify.
  • The optimizer's ceiling depends on the metric and the eval set, so the most valuable work for an FDE is defining what "correct" means together with the customer.

The most famous chain-of-thought prompt is a single human-written instruction telling the model to "think step by step." It was once beaten by an algorithm leveraging language models. The Automatic Prompt Engineer (APE) method found a longer variant that asks the model to solve the problem step by step "to ensure we get the right answer."

According to DAIR.AI's Prompt Engineering Guide, this wording improved performance on two math benchmarks, MultiArith and GSM8K.

The key is how that sentence came about. Nobody sat down and came up with it; it was searched for and selected by an algorithm, just as engineers tune hyperparameters.

Forward Deployed Engineers (FDEs) run into this problem almost every week. On-site with a customer, you might spend an entire week tuning prompts for a classification or extraction pipeline, only for the customer to switch models and force you to start over. DSPy turns this manual tuning into an optimization problem, with the customer's eval set as the objective function.

Treating prompts as parameters

The idea of using algorithms to find prompts is clearly laid out in the paper "Large Language Models Are Human-Level Prompt Engineers" by Zhou et al., released on arXiv on November 3, 2022. APE's mechanism is quite simple: an LLM proposes a batch of candidate instructions, and the system searches among them for the one with the highest score.

On 19 of 24 NLP tasks, instructions generated by APE matched or exceeded those written by human annotators.

DSPy applies the same logic at the pipeline level. A paper by Khattab, Zaharia, Potts et al., released on October 5, 2023, describes a compiler that can optimize any DSPy pipeline to maximize a given metric.

DSPy's modules are parameterized, meaning they can learn—for example, prompts or sets of few-shot examples.

Stanford NLP's official README describes DSPy as a framework for "programming" language models rather than "writing prompts." Its full name is Declarative Self-improving Python. According to the README, the framework includes algorithms that optimize both prompts and model weights.

When is DSPy worth using?

DSPy works best in scenarios that meet three conditions simultaneously: the task has measurable answers; the customer has labeled data or is willing to label it; and the pipeline's models or requirements will keep changing. When the first condition doesn't hold—for example, when the customer just wants answers that "sound better" but no one can articulate what better means—the optimizer has nothing to work with.

Suppose a bank wants to automatically sort complaint emails into 6 categories so each email reaches the right department. The operations team has labeled 300 emails. You use 200 as optimization data and hold out 100 as a holdout set that the optimizer never sees. The metric is a simple function: 1 point if the predicted label matches the human label, 0 if not.

The illustrative code below shows the three parts: a module that declares inputs and outputs, a metric function, and a compile call. This is only illustrative—for the optimizer's class names and specific parameters, refer to the documentation for your version of DSPy.

import dspy

# 模块:声明任务,而不是写提示词
classify = dspy.Predict("email -> complaint_category")

# 指标:与人工标签一致得 1,否则得 0
def label_match(example, prediction, trace=None):
    return prediction.complaint_category == example.complaint_category

# 编译:优化器用 200 封邮件尝试不同的指令和少样本示例
optimizer = dspy.BootstrapFewShot(metric=label_match)
optimized = optimizer.compile(classify, trainset=optimization_emails)

# 只报告 100 封留出邮件上的得分

Suppose the hand-written prompt scores 78/100 on the holdout set. You run the compiler, letting it try various approaches and score each one with the metric. If the best approach reaches 86/100 on the holdout set, the gap is 8 more emails correctly sorted per 100.

At 5,000 emails per month, the bank misroutes roughly 400 fewer emails per month. That's a number an operations director understands immediately.

TaskWho does it
Define what "correct" meansFDE together with the customer
Label data and set aside a holdout setCustomer, reviewed by the FDE
Generate and test prompt candidatesOptimizer
Analyze the remaining errors on the holdout setFDE

The value is in the last row. The 14 emails still misclassified often point to an ambiguous category or inconsistent labeling, which becomes the agenda for the next meeting with the customer.

The optimizer is only loyal to the metric

DSPy only optimizes what you measure, nothing more. If the metric only checks output format and ignores content, you get a prompt that is very good at returning the correct format. If the eval set is too small or biased, the prompt will overfit those few dozen samples.

So report holdout set scores, not scores on the optimization data.

Factor in cost too. Each candidate tried means another batch of model calls. So start with small datasets and cheap models before scaling up.

Even so, prompt optimization remains more cost-effective than the alternatives. GEPA is a reflective prompt evolution method published by Agrawal, Khattab et al. in 2025. Its authors note that reinforcement learning methods like GRPO often require thousands of rollouts to learn a new task.

Across six tasks, GEPA averaged 6% higher than GRPO, up to 20% on some tasks, while using up to 35 times fewer rollouts. The lesson for FDEs: before proposing fine-tuning to a customer, push prompt optimization to its limits first.

What to learn first so you can use it right away

Start by practicing writing metrics and building eval sets, because DSPy can't do that part for you. The API can wait. Then read the APE abstract to understand the "propose candidates and score them" loop; then read the DSPy paper to see how modules, metrics, and the compiler fit together.

When reading job descriptions for FDE or AI engineer roles, watch for mentions of "eval," "prompt optimization," or DSPy by name. On your resume, don't write "proficient in prompt engineering"; instead write a sentence with numbers: how many samples your eval set had, that you used automatic optimization, and how much holdout accuracy improved.

When a customer switches models, hand-written prompts become obsolete. A well-defined eval set keeps working; next time, you just rerun the compiler.

Was this article helpful?

Thanks for your feedback!

5 sources

Next on the roadmap · Phase 3: AI applications AutoGen enters maintenance mode—what FDEs should ask first when choosing a framework Microsoft has been steering new users toward Agent Framework; when choosing, first ask who maintains it, then ask whether the security team will approve.