Skip to content
sinc-LLMBook a 15-minute call
Page signal: 16 sections as samples, joined by sinc reconstruction; computed from this page's text.

Prompt Compilation: How DSPy and Automatic Prompt Optimizers Replace Hand-Tuned Prompts

A practical guide to compiling prompts with DSPy, MIPROv2, GEPA, APE, and OPRO, from dev sets and metrics to release and review.

Quick Answer & Verified Key Facts

Direct Answer: Prompt compilation automates prompt optimization by declaring inputs/outputs, defining metrics, and using optimizers like DSPy to generate high-scoring prompts, replacing manual tuning.

On this page

Prompt compilation means you write what a step should do, pick a metric, and let an optimizer search for the prompt text and examples that score best. DSPy is the best known tool for this. It works well when you have a fair dev set and a metric you trust, and it fails quietly when you do not.

By Mario AlexandreLLM Performance & Reliability

Prompt compilation in plain terms

Prompt compilation means you stop editing prompt text by hand. You state what a step takes in and what it must give back. You write a metric that scores an answer. Then a program, called an optimizer, writes and tests many prompts for you and keeps the one that scores best on your data.

The name comes from the DSPy paper. Its authors point out that most LLM pipelines are built from hard-coded prompt templates, which are long strings found by trial and error. Their fix is a compiler that tunes a pipeline to raise a metric you choose. The prompt becomes a build output, not a hand-made file.

Think of a normal compiler. You write code that says what should happen. The compiler picks the machine steps. In prompt compilation, you write a short spec of the task. The optimizer picks the words of the instruction and the worked examples that go into the prompt.

This shift matters for teams that run many LLM steps in a chain. One hand-tuned prompt is easy to keep. Ten prompts that feed each other are not. When you change one, the others may break. A compiler can tune them together against one end goal.

How this guide differs from tool lists

Our PromptPerfect alternatives page is a list of tools, and DSPy is one entry on it. Our guide on LLM prompt optimization covers how a person improves a prompt by hand, and best prompt frameworks covers ways to structure prompt text. This page is about something else. It is about letting code search for the prompt, and about the test and release work that makes that safe.

So you will not find a ranking here. You will find how the search works, what data it needs, how it goes wrong, and how to ship its output like any other build. If you want a tool list, start with the list page. If you want to run a compiler and trust what it gives you, read on.

The DSPy building blocks: signatures, modules, metrics, optimizers

DSPy splits a prompt into four parts. A signature says what goes in and out. A module decides how the model is called. A metric scores the output. An optimizer changes the prompt to raise the score.

Signatures

The DSPy signatures guide defines a signature as a declarative spec of the input and output behavior of a module. You say what the model must do, not how to ask. The shortest form is a string.

qa = dspy.Predict("question -> answer")

That line means one input field named question and one output field named answer. Per the guide, both default to the str type when you give no type. You can add more fields and types, such as a list of context passages and a typed answer.

Field names matter. The guide says names express semantic roles, so a field called sql_query tells the model something that a field called output does not. Pick clear names, but do not polish them for hours. The same guide warns against tuning keywords by hand too early, since that is the job of the optimizer.

Output fields are also checked. The guide notes that when the model reply lacks a declared output field, the adapter raises an AdapterParseError. That gives you a hard failure instead of a silent bad answer. If you need strict shapes, pair this with the ideas in our guide on constrained decoding and JSON Schema outputs.

Modules

A module wraps a signature with a way of calling the model. dspy.Predict asks for the output once. Other modules add a reasoning field or loop over tools. You chain modules in normal Python to build a pipeline.

The key idea from the DSPy paper is that modules have parameters. They can learn by creating and collecting worked examples, called demonstrations or demos. Those demos, plus the instruction text, are the knobs the optimizer turns.

Metrics

The DSPy optimizer docs describe a metric as a function that scores the output of your program, where higher is better. It can be as plain as exact match. It can also be a check on format, a check on facts, or a call to a judge model.

The metric is the most important thing you write. The optimizer will chase it with no sense of what you meant. If the metric rewards short answers, you get short answers. If it rewards a keyword, you get the keyword. Our guide on LLM as judge evaluation covers how to build a judge you can trust.

Optimizers

The same docs define an optimizer as an algorithm that tunes the prompts and, in some cases, the model weights of a DSPy program to raise your metric. They were once called teleprompters, and you will still see that name in older code. Each optimizer takes three things: your program, your metric, and a few training inputs.

The docs say the training set can be very small, as few as 5 or 10 examples, and may hold inputs with no labels. That is a low bar to start. It is not a low bar to finish, as later sections show.

A full call is short.

tp = dspy.MIPROv2(metric=my_metric)
compiled = tp.compile(program, trainset=train)

The output is a new program with the same steps. What changed is the text and the demos inside each step.

How optimizers search for better prompts

Every prompt optimizer runs the same loop. It proposes a change to the prompt, runs the program on some examples, scores the results with your metric, and keeps what helps. The methods differ in what they change and how they pick the next try.

The MIPRO paper gives a clean way to see the search space. It splits the problem into two parts for each module: the free-form instruction and the few-shot demos. Some optimizers only touch demos. Some only touch the instruction. The stronger ones tune both, and do it across every module at once.

There is one more hard part. In a chain of steps, you only see the score at the end. You do not have labels for what each middle step should have said. The MIPRO paper names this as the core task: raise a downstream metric with no labels for each module and no gradients. Each optimizer below handles that gap in its own way.

Bootstrapped few-shot demos

Bootstrapping is the oldest and simplest trick in DSPy. The optimizer runs your program on training inputs. It records what each module took in and gave back. If the final output passes your metric, those records become demos for each module.

The DSPy optimizer docs say BootstrapFewShot uses a teacher module, which by default is your own program, to build full demos for every stage. The metric checks each demo, and only those that pass go into the compiled prompt. This is how DSPy gets demos for middle steps that you never labeled. A good final answer vouches for the steps that led to it.

BootstrapFewShotWithRandomSearch repeats this many times with different random sets of demos. It then keeps the best program found. That costs more model calls, but it is less likely to lock in a lucky or unlucky first draw.

If you already know how few-shot demos shape a model, our few-shot prompting guide covers the basics. Bootstrapping is the same idea, except the demos are picked by a score instead of by taste.

Instruction proposal

The second knob is the instruction text. Here the optimizer asks a model to write candidate instructions, then tests them. The APE paper framed this early. It treats the instruction as the program and searches a pool of candidates proposed by an LLM to raise a score function.

APE matters because it showed the idea works at all. According to its authors, the instructions it found matched or beat instructions written by human annotators on 19 of 24 tasks. That is a claim about those tasks and those models. It does not promise the same on yours, which is why you still need your own dev set.

In DSPy, the COPRO optimizer refines instructions with a hill-climbing search. MIPROv2 goes further by writing instructions that are aware of your data and your demos.

Bayesian search in MIPROv2

This optimizer tunes both instructions and demos. It searches with a model of what has worked so far. The DSPy docs walk through it in three stages.

  1. Bootstrap. It runs your program many times across inputs and collects traces for each module. It keeps only traces from runs your metric scored well.
  2. Grounded proposal. It looks at your program code, your data, and those traces. Then it drafts many candidate instructions for every prompt.
  3. Discrete search. It samples mini-batches from the training set. It picks one instruction and one set of demos for each module, builds the whole program, and scores it on the batch. The scores feed a surrogate model that guides the next pick.

The docs call this Bayesian Optimization over instructions and demos across modules. In plain terms, the surrogate guesses which mix is likely to score well, so the search spends its budget on good bets instead of random ones. The MIPRO paper adds that it uses noisy mini-batch scores to learn this surrogate, which keeps each trial cheap.

How much does it help? According to the MIPRO paper, it beat baseline optimizers on five of seven multi-stage programs using Llama-3-8B, by as much as 13% accuracy. Note the shape of that claim. It won on most tasks, not all, and the top gain was the best case.

Reflective evolution in GEPA

This optimizer takes a different path. Instead of only reading a number from the metric, it reads what happened. The GEPA paper describes how it samples trajectories, such as reasoning, tool calls, and tool outputs. It then reflects on them in natural language to find problems, proposes prompt updates, tests them, and combines lessons from the Pareto frontier of its own attempts.

The Pareto part is worth a sentence. GEPA does not keep just one best prompt. It keeps a set of prompts where each one is best on some slice of the examples. It can then merge ideas from prompts that are strong on different cases.

The DSPy docs add a practical point: GEPA can use domain-specific text feedback. So your metric can return a score plus a short note, like "the date format is wrong" or "cited a source not in context." That note gives the reflection step much more to work with than a bare zero.

The reported gains are large. Per the GEPA paper, it beat the RL method GRPO by 6% on average and by up to 20%, while using up to 35x fewer rollouts. According to the same paper, it also beat MIPROv2 by over 10%. Treat these as results on the paper's six tasks. They are a reason to try GEPA, not a forecast for your system.

APE and OPRO: the research roots

Two papers shaped how people think about this field. APE, covered above, showed a model can write and pick its own instructions. OPRO framed the model itself as the optimizer.

In OPRO, each step builds a prompt that lists earlier candidate solutions with their scores. The model reads that list and writes new candidates. Those are scored and added back for the next round. Over time, the list acts like a memory of what worked.

According to the OPRO paper, the best optimized prompts beat human-designed prompts by up to 8% on GSM8K and by up to 50% on Big-Bench Hard tasks. Again, "up to" means the best case across their runs.

DSPy does not ship APE or OPRO by those names in its main optimizer list. But the ideas run through its tools. Proposing instructions with a model comes from this line of work. So does the habit of feeding scores back into the next proposal.

Choosing an optimizer for your data and budget

Pick the optimizer by how much data you have and how many model calls you can spend. The DSPy docs say plainly that finding the right optimizer and setup takes experiments. They also give a starting map, which the table below follows.

Your situation Start with What it tunes Main risk
About 10 labeled examples BootstrapFewShot Few-shot demos Fits a tiny set too closely
50 or more examples BootstrapFewShotWithRandomSearch Demos, with many random tries More calls, still demo only
Want a zero-shot prompt MIPROv2 set for 0-shot Instruction text only Instruction drifts from intent
200 or more examples and budget for 40 or more trials MIPROv2 Instructions and demos together Cost, and overfit with less data
Rich failure notes, agent or tool traces GEPA Instructions, guided by reflection Feedback text that is vague or biased
A strong prompted program, need low cost per call BootstrapFinetune Weights of a smaller model You now own a fine-tuned model

A few notes on the table. The docs tie the 200 example figure to MIPROv2 directly, as the amount needed to prevent overfitting on long runs. The 10 and 50 example rules of thumb come from the same page. These are starting points, not laws.

The last row is not prompt tuning at all. The docs say BootstrapFinetune distills a prompt-based program into weight updates. You keep the same steps, but each step runs on a tuned model instead of a prompted one. That is a bigger change to own, with its own release and rollback work.

Optimizers also stack. The docs note that you can run MIPROv2, then feed its output back into MIPROv2 again, or into BootstrapFinetune. Stacking can help, but each pass is another chance to overfit. Hold out a test set that no pass ever sees.

What a run costs

Cost depends on calls, so you can estimate it before you start. The DSPy docs say a typical simple run costs on the order of $2 USD and takes around ten minutes. They also warn that very large models or very large datasets cost more.

Here is illustrative arithmetic, not a measured run. Suppose MIPROv2 runs 40 trials. Each trial scores a mini-batch of 25 examples. Your program makes 3 model calls per example. That is 40 times 25 times 3, or 3,000 calls for search alone. Add the bootstrap stage and the instruction drafts, and you might land near 4,000 calls.

Now price it. Suppose each call uses 1,500 input tokens and 200 output tokens. At 4,000 calls that is 6 million input tokens and 0.8 million output tokens. Multiply by your model's rates to get a dollar figure. Do this before the run, not after the bill.

What you need before you optimize

You need three things before an optimizer can help: a dev set that looks like real traffic, a metric that matches what users care about, and a split that keeps some data unseen. Skip any one and the compiler will still report a high score. It just will not mean much.

A dev set that looks like production

The dev set is the pool of examples you tune and test on. It should match the mix of inputs your system really gets. That means common cases, rare cases, and the inputs that break things today.

Start with real logs if you have them. Strip private data first. Group them by type, then sample so that rare but costly types are not lost. Our guide on LLM evaluation dataset design covers how to size and balance a set like this.

The DSPy docs say you can start with only 5 or 10 inputs. That is fine for a first look. It is not enough to trust a release. With 10 examples, one flip moves your score by ten points. You cannot tell skill from luck at that size.

A metric you would bet on

Write the metric as code you can read in one minute. Test it before you test the prompt. Feed it known good and known bad outputs, and make sure it scores them the way a careful person would.

Good metrics often combine checks. A format check catches broken output. A content check catches wrong facts. A length or cost check stops the optimizer from padding answers. You can sum them with weights, or require a pass on the hard checks before you count the soft ones.

If you use a judge model inside the metric, treat it as a second system under test. Check how often it agrees with people on a sample. Freeze its prompt and version while you compile, or your scores will drift for reasons that have nothing to do with your program.

A split that keeps a secret

Split your data three ways. The train set feeds the optimizer. The validation set picks between candidates. The test set is opened once, at the end, to judge the winner.

The reason is simple. The optimizer looks at train and validation scores many times. Anything it sees that often, it can fit. Only data it never saw tells you how the prompt will do on new inputs.

Worked example: sizing the split

Here is illustrative arithmetic for a support ticket classifier. Suppose you have 400 labeled tickets. You put 200 in train, 100 in validation, and 100 in test.

Say the uncompiled program gets 72 of 100 test tickets right. After compiling, it gets 81 of 100. That looks like a 9 point gain. But how sure can you be?

With 100 test items and a rate near 0.8, the standard error is about the square root of 0.8 times 0.2 over 100. That is the square root of 0.0016, or 0.04. So each score is give or take about 4 points. But you are comparing two scores, and both carry noise. The standard error of the gap is the square root of 0.72 times 0.28 over 100 plus 0.81 times 0.19 over 100. That comes to about 6 points. A 9 point gap is only about 1.5 times that, so two separate scores cannot show the gain is real.

Now shrink the test set to 20 tickets. Each score then has a standard error of about 9 points, and the gap about 13. A 9 point gap is well inside the noise. This is why a small test set can make a weak prompt look like a win.

A paired check helps. Run both programs on the same test items and count the items where only one is right. If the new program wins 14 of those and loses 5, the net gain is still 9 points. Now a simple sign test on those 19 split items, such as McNemar's test, puts the result just past the usual 5 percent bar. The paired view removes the noise from item difficulty, which is why it can confirm a gain that two separate scores cannot.

Keeping the optimizer from overfitting

The failure here is that the compiled prompt learned your dev set instead of your task. The fix is to give the optimizer less room to cheat and to check its work on data it never touched.

An optimizer is a search over many prompts. The more prompts it tries, the more likely one scores high by chance. That prompt may lean on quirks of your examples, like a name that shows up often or a format only your labeler used. On new data, the gain fades.

The DSPy docs make this point in their own advice. They suggest about 200 examples or more before long MIPROv2 runs, to prevent overfitting. Treat that as a floor for heavy search, not a target.

Practical guards

  • Hold out a test set and lock it. Store it apart from the rest. Do not look at its failures until the final check, or you will start tuning to it by hand.
  • Watch the gap. Track the score on train, validation, and test. If train climbs while validation stalls, stop the run.
  • Limit the budget. Fewer trials and fewer demos mean fewer ways to fit noise. Raise the budget only when the held-out score keeps rising with it.
  • Check for leaks. Make sure no test item, or a near copy, sits in train. Bootstrapped demos can copy a train input word for word into the prompt.
  • Read the demos. Open the compiled prompt and read every demo. If one looks odd, or contains private data, remove it.
  • Rerun with a new seed. If a second run with a different seed gives a very different score, your result is fragile.

Metric gaming

A second kind of overfit is to the metric itself. If your metric checks that the answer cites a source, the optimizer may learn to cite any source. If it checks length, it may learn to pad. The prompt scores well and helps no one.

The defense is a second check the optimizer never sees. Keep a small set of human reviews or a different judge for the final test. If the main metric rises while the second check stays flat, the optimizer found a loophole.

Recompiling when the model changes

A compiled prompt is tuned for one model. When you change the model, recompile and retest. Do not assume the old prompt carries over.

The reason is in how the search works. The optimizer kept the instruction and demos that scored best with a given model. A new model reads text in its own way. A demo that guided the old model may confuse the new one. An instruction that fixed a quirk may now be dead weight.

This is one of the real wins of compilation. With hand-written prompts, a model swap means days of manual edits. With a compiled program, your signatures, modules, metric, and data stay the same. You point the program at the new model and run the optimizer again.

Triggers for a recompile

  • New model or new model version. This includes silent updates behind the same name, if your provider makes them.
  • New decoding settings. A change in temperature or max tokens can shift which prompt wins.
  • Shift in traffic. If new kinds of inputs show up, your dev set is stale. Add samples, then recompile.
  • Metric change. If you change what "good" means, every prior result is out of date.
  • Longer inputs. If your context grows, check that the compiled prompt still works at that length. Our guide on effective context length testing explains why a model may not use long inputs as well as its spec suggests.

Compare before you switch

Run the old compiled program on the old model and the new compiled program on the new model. Use the same locked test set for both. Also run the old prompt on the new model, so you can see how much of the gain came from the model and how much from recompiling.

That three-way view tells you what to ship. If the new model with the old prompt is already as good, you may not need the recompile. If the recompiled version wins by a clear margin on paired items, ship it.

Compiled prompts as release artifacts

Treat a compiled prompt like a build output. Save it, version it, review it, and release it with the same care as code. The DSPy docs give you the first step: a compiled program can be saved to a file with save and restored later with load.

compiled.save("qa_v7.json")

That file holds the instructions and demos the optimizer chose. It is small and readable. It belongs in version control, next to the code that loads it.

What to record with each build

A saved file alone is not enough to rebuild or audit a result. Store a short manifest with it.

  • The model name and version used to compile.
  • The optimizer name and its settings, including the seed.
  • A hash or version tag of the train, validation, and test sets.
  • The metric code version.
  • Scores on train, validation, and the locked test set.
  • The DSPy version.

With this, anyone can answer two key questions later. What exactly is running? Can we rebuild it?

Review the diff, not just the score

When a new build lands, open a diff against the last release. Read the new instruction text. Read every new demo. A score gain is not a reason to skip this step.

Reviewers should look for a few things. Does any demo hold private data copied from a training input? Does the instruction promise something your product does not do? Did a safety rule from the old prompt vanish? Did the prompt grow so long that cost or latency will jump?

Gate the release with tests

Run the compiled program through your normal regression suite before release. Our guide to prompt regression testing shows how to build that suite. The compiled score on the dev set is one gate. The regression suite is a second, broader gate.

Then roll out in stages. Send a small share of traffic to the new build, watch your live metrics, and keep the old file ready to load. Since the artifact is just a file, rollback is a one-line change.

When hand-written prompts still win

Compilation is not always the right tool. Hand-written prompts still win when you lack data, lack a good metric, or need a rule that must hold word for word.

The DSPy docs are fair about this. The signatures guide says that in many cases compiling leads to better prompts than people write. It also gives the reason: not because optimizers are more creative, but because they can try more things and tune the metric directly. If you cannot give them a metric worth tuning, that edge is gone.

Cases where a person should write the prompt

  • No metric yet. If you cannot score an answer in code, you are not ready to compile. Write the prompt by hand, collect outputs, and learn what good looks like.
  • Tiny or new tasks. For a one-off task or a quick prototype, the setup cost is larger than the gain.
  • Policy text. Legal notices, safety rules, and brand rules must say exact things. Write them yourself and keep them out of the optimizer's reach. Let it tune the rest.
  • Strict audit needs. Some teams must explain each word of a prompt. A human-written prompt is easier to defend.
  • A metric that is cheap to game. If the only metric you can afford rewards surface traits, the optimizer will find them. A careful person may do better.

A mixed approach

Many teams land in the middle. They write the fixed parts by hand, like safety rules and output format. They let the optimizer tune the task instruction and pick the demos. The fixed parts stay stable across builds, and the tuned parts improve over time.

Prompt frameworks help with the hand-written part. If you want a structure for that, see our guide on best prompt frameworks. For teams that want help designing the metric, dev set, and release gates, sinc-LLM offers solutions built around testing first.

A step-by-step compilation workflow

Here is a workflow you can follow from first draft to release. Each step has a clear output, so you can stop and review before you move on.

  1. Write the task as signatures. List each step in your pipeline. For each one, name the input and output fields in plain words. Keep the first draft simple.
  2. Build the program with plain modules. Chain the steps in Python. Run it on a few inputs by hand and make sure it works end to end.
  3. Collect the dev set. Pull real inputs, remove private data, and label them. Aim for at least a few hundred examples if you plan a long search.
  4. Split the data. Make train, validation, and test sets. Lock the test set where the optimizer cannot reach it.
  5. Write and test the metric. Score a mix of good and bad outputs by hand first. Fix the metric until it agrees with you.
  6. Score the baseline. Run the uncompiled program on validation and test. Save these numbers. Every later result is compared to them.
  7. Pick an optimizer. Use the table above. Start with the cheapest one that fits your data, and estimate the call count first.
  8. Compile. Run the optimizer on train, with validation for picking. Log the settings and seed.
  9. Inspect the output. Read the new instructions and every demo. Remove anything private, odd, or off-policy.
  10. Score on the locked test set. Run the compiled and baseline programs on the same test items. Compare paired wins and losses.
  11. Run the regression suite. Check the edge cases and safety tests that your dev set may not cover.
  12. Save and version. Save the compiled program, write the manifest, and commit both.
  13. Release in stages. Ship to a small share of traffic. Watch live metrics. Keep the old file ready for rollback.
  14. Plan the next compile. Note what would trigger a recompile, such as a model change or new kinds of inputs.

This list is long on purpose. The compile step itself is two lines of code. Nearly all the work is in the data, the metric, and the checks around it.

Failure modes and how to spot them

Most compiled prompts that fail in production fail in a few known ways. The table below lists them with a sign you can watch for and a fix.

Failure mode Sign you can detect Fix
Overfit to the dev set Train score rises, test score flat or down More data, smaller budget, locked test set
Metric gaming Main metric up, human review flat Add a hidden second check, tighten the metric
Leaked test data Test score far above validation Dedupe train against test, rebuild the split
Private data in demos Names, emails, or IDs in the saved file Scrub inputs, review every demo before release
Stale build after model change Live scores drop after a provider update Pin model versions, recompile on change
Judge drift Scores move with no program change Freeze the judge model and prompt during compile
Cost blowup Prompt length jumps between builds Track tokens per call as a release gate
Lucky seed A rerun scores far lower Run two or more seeds, report the spread

Signs inside the compiled file

Some problems show up only when you read the file. Look for demos that all share one pattern, such as the same answer label. That can push the model to favor that label. Look for an instruction that names a dataset quirk, like a field that only your test harness adds.

Also check the length. Each demo adds tokens to every call. If a build adds eight long demos, your cost per call may double with no gain worth that price. Make tokens per call a number you review, not a surprise.

Signs in production

After release, watch the same metric you compiled on, plus a few others. Track the parse failure rate, since a missing output field raises an error in DSPy. Track latency and cost per call. Sample live outputs for human review each week.

If live scores slide while nothing in your code changed, suspect the model, the traffic mix, or the judge. Each one is a reason to refresh the dev set and recompile.

Prompt compilation checklist

Use this list before you ship a compiled prompt.

  • Signatures name each input and output clearly.
  • The dev set reflects real traffic, including rare and costly cases.
  • Train, validation, and test sets are split, and the test set is locked.
  • The metric was tested on known good and bad outputs.
  • Any judge model is pinned to a fixed version and prompt.
  • The baseline score is saved for comparison.
  • The optimizer choice fits your data size and budget.
  • Call count and cost were estimated before the run.
  • Every instruction and demo in the output was read by a person.
  • No private data appears in any demo.
  • Paired test results show a gain beyond noise.
  • The regression suite passes.
  • The saved program and manifest are in version control.
  • A rollback path is ready.
  • Recompile triggers are written down.

If every box is checked, you have more than a better prompt. You have a prompt you can rebuild, explain, and roll back, which is the real point of treating prompts as compiled output.

Frequently asked questions

What does it mean to compile a prompt?

Compiling a prompt means you describe a task as inputs and outputs, write a metric, and let an optimizer pick the instruction text and worked examples. The optimizer tries many versions, scores each on your examples, and keeps the best one. The result is a saved file that you can test, version, and release like any other build output.

Is DSPy the same as a prompt template library?

No. A template library helps you fill in text that you wrote. DSPy asks you to declare what each step takes in and gives back, then uses an optimizer to write and tune the prompt for you. You still write Python to connect the steps, but the prompt wording and the few-shot demos come out of a search against your metric.

How many examples do I need to start with DSPy?

The DSPy docs say you can start with as few as 5 or 10 inputs, and they do not all need labels. That is enough to try the tool. For long MIPROv2 runs, the same docs suggest about 200 examples or more to avoid overfitting. You also need a separate test set that the optimizer never sees.

Which DSPy optimizer should I try first?

Start small. With about 10 examples, try BootstrapFewShot. With 50 or more, try BootstrapFewShotWithRandomSearch. If you have a few hundred examples and budget for longer runs, try MIPROv2. If your metric can return text notes about failures, GEPA can use those notes to guide its search.

Does a compiled prompt work on a different model?

Not reliably. The optimizer picked the instruction and demos that scored best with one model. A different model may read them in a different way. When you change models, keep your signatures, metric, and data, and run the optimizer again. Then compare the old and new builds on the same locked test set before you switch.

How do I stop the optimizer from overfitting?

Lock a test set the optimizer never sees and judge the final build only on it. Track train and validation scores during the run and stop if they split apart. Use enough data for the search budget, limit trials, read every demo, check for leaks between splits, and rerun with a second seed to see if the gain holds.

When should I write a prompt by hand instead?

Write by hand when you have no metric you trust, very little data, or text that must say exact things, such as legal or safety rules. Many teams mix both: they write fixed rules by hand and let the optimizer tune the task instruction and pick the demos. That keeps policy stable while the rest improves.

Sources

  1. DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines: The paper that introduced DSPy and the idea of a compiler that tunes LM pipelines against a metric.
  2. Optimizing Instructions and Demonstrations for Multi-Stage Language Model Programs: The MIPRO paper, covering instruction proposal, mini-batch scoring, and a surrogate model for search.
  3. Large Language Models as Optimizers: The OPRO paper, where a model reads past solutions and scores to propose new prompts.
  4. Large Language Models Are Human-Level Prompt Engineers: The APE paper, which searches a pool of model-written instructions to raise a score.
  5. GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning: The GEPA paper, on natural language reflection over trajectories and a Pareto set of prompts.
  6. DSPy docs: Optimizers: Official guide to DSPy optimizers, their inputs, MIPROv2 stages, selection advice, cost, and save and load.
  7. DSPy docs: Signatures: Official guide to signatures, field names, types, and output field checks.
Original source record

Skip to content

sinc-LLMAboutBlogServices