dsir 0.1.1

DSPy-shaped library for programming language models in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use anyhow::{Result, anyhow};
use bon::Builder;

use crate::evaluate::{TypedMetric, average_score};
use crate::optimizer::{
    Optimizer, evaluate_module_with_metric, predictor_names, with_named_predictor,
};
use crate::predictors::Example;
use crate::{BamlType, BamlValue, Facet, Module, Signature, SignatureSchema};

/// A single program execution trace: input, outputs, and score.
///
/// Used internally by [`MIPROv2`] to collect execution data that informs
/// candidate instruction generation. Traces with higher scores guide the
/// optimizer toward better instructions.
#[derive(Clone, Debug)]
pub struct Trace<S: Signature> {
    pub input: S::Input,
    pub outputs: BamlValue,
    pub score: Option<f32>,
}

impl<S: Signature> Trace<S> {
    pub fn new(input: S::Input, outputs: BamlValue, score: Option<f32>) -> Self {
        Self {
            input,
            outputs,
            score,
        }
    }

    pub fn format_for_prompt(&self) -> String {
        let mut result = String::new();
        result.push_str("Input:\n");

        result.push_str(&format!("  {}\n", self.input.to_baml_value()));

        result.push_str("Output:\n");
        result.push_str(&format!("  {}\n", self.outputs));

        if let Some(score) = self.score {
            result.push_str(&format!("Score: {:.3}\n", score));
        }

        result
    }
}

/// An instruction candidate with its evaluated score.
///
/// Generated by [`MIPROv2`]'s candidate generation step, then scored by
/// evaluating the module with this instruction on a minibatch.
#[derive(Clone, Debug)]
pub struct PromptCandidate {
    pub instruction: String,
    pub score: f32,
}

impl PromptCandidate {
    pub fn new(instruction: String) -> Self {
        Self {
            instruction,
            score: 0.0,
        }
    }

    pub fn with_score(mut self, score: f32) -> Self {
        self.score = score;
        self
    }
}

/// Library of general prompting best practices used to seed candidate generation.
///
/// These tips are appended to candidate instructions during [`MIPROv2`] optimization
/// to introduce diversity. Each candidate gets a different tip from the rotation.
pub struct PromptingTips {
    pub tips: Vec<String>,
}

impl PromptingTips {
    pub fn default_tips() -> Self {
        Self {
            tips: vec![
                "Use clear and specific language".to_string(),
                "Provide context about the task domain".to_string(),
                "Specify the desired output format".to_string(),
                "Use chain-of-thought reasoning for complex tasks".to_string(),
                "Include few-shot examples when helpful".to_string(),
                "Break down complex instructions into steps".to_string(),
                "Use role-playing (e.g., 'You are an expert...') when appropriate".to_string(),
                "Specify constraints and edge cases".to_string(),
                "Request explanations or reasoning when needed".to_string(),
                "Use structured output formats (JSON, lists, etc.) when applicable".to_string(),
                "Consider the model's strengths and limitations".to_string(),
                "Be explicit about what to avoid or exclude".to_string(),
                "Use positive framing (what to do vs. what not to do)".to_string(),
                "Provide examples of both correct and incorrect outputs when useful".to_string(),
                "Use delimiters or markers to separate different sections".to_string(),
            ],
        }
    }

    pub fn format_for_prompt(&self) -> String {
        self.tips
            .iter()
            .enumerate()
            .map(|(i, tip)| format!("{}. {}", i + 1, tip))
            .collect::<Vec<_>>()
            .join("\n")
    }
}

/// Trace-guided instruction optimizer.
///
/// MIPROv2 (Multi-prompt Instruction PRoposal Optimizer v2) works in three phases:
///
/// 1. **Trace collection** — runs the module on the trainset to collect execution
///    traces with scores
/// 2. **Candidate generation** — uses the traces and prompting tips to generate
///    `num_candidates` instruction variants per predictor
/// 3. **Trial evaluation** — evaluates up to `num_trials` candidates on a minibatch,
///    keeps the best
///
/// Unlike [`GEPA`](crate::GEPA), MIPROv2 does not require feedback — only numerical scores.
/// Unlike [`COPRO`](crate::COPRO), it uses execution traces to inform candidate generation
/// rather than
/// blind search.
///
/// # What it doesn't do
///
/// MIPRO only optimizes instructions, not demos. Per-predictor demo mutation from
/// trace data is the next step — Python DSPy does this and it matters. The
/// `TODO(trace-demos)` markers in the source track this gap.
///
/// # Hyperparameters
///
/// - **`num_candidates`** (default: 10) — instruction variants generated per predictor.
/// - **`num_trials`** (default: 20) — maximum candidates evaluated per predictor.
///   If `num_trials` < `num_candidates`, only the first `num_trials` are evaluated.
/// - **`minibatch_size`** (default: 25) — examples per candidate evaluation.
///
/// # Cost
///
/// Roughly `num_predictors × (trainset_size + num_trials × minibatch_size)` LM calls.
///
/// ```ignore
/// let mipro = MIPROv2::builder()
///     .num_candidates(10)
///     .num_trials(20)
///     .build();
/// mipro.compile(&mut module, trainset, &metric).await?;
/// ```
#[derive(Builder)]
pub struct MIPROv2 {
    /// Instruction variants generated per predictor.
    #[builder(default = 10)]
    pub num_candidates: usize,

    /// Maximum candidates evaluated per predictor.
    #[builder(default = 20)]
    pub num_trials: usize,

    /// Examples per candidate evaluation.
    #[builder(default = 25)]
    pub minibatch_size: usize,
}

impl MIPROv2 {
    async fn generate_traces<S, M, MT>(
        &self,
        module: &M,
        examples: &[Example<S>],
        metric: &MT,
    ) -> Result<Vec<Trace<S>>>
    where
        S: Signature,
        S::Input: Clone,
        M: Module<Input = S::Input>,
        MT: TypedMetric<S, M>,
    {
        let mut traces = Vec::with_capacity(examples.len());
        for example in examples {
            let input = example.input.clone();
            let predicted = module.call(input).await.map_err(|err| anyhow!("{err}"))?;
            let outcome = metric.evaluate(example, &predicted).await?;
            let (output, _) = predicted.into_parts();
            traces.push(Trace::new(
                example.input.clone(),
                output.to_baml_value(),
                Some(outcome.score),
            ));
        }

        Ok(traces)
    }

    pub fn select_best_traces<'a, S: Signature>(
        &self,
        traces: &'a [Trace<S>],
        num_select: usize,
    ) -> Vec<&'a Trace<S>> {
        let mut scored_traces: Vec<_> = traces.iter().filter(|t| t.score.is_some()).collect();

        scored_traces.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        scored_traces.into_iter().take(num_select).collect()
    }

    fn generate_candidate_instructions<S: Signature>(
        &self,
        program_description: &str,
        traces: &[Trace<S>],
        num_candidates: usize,
    ) -> Vec<String> {
        let tips = PromptingTips::default_tips();
        let score_hint = traces.iter().filter_map(|t| t.score).fold(0.0f32, f32::max);

        (0..num_candidates)
            .map(|idx| {
                let tip = &tips.tips[idx % tips.tips.len()];
                format!(
                    "{program_description}\n\nOptimization candidate {}:\n- {}\n- Target score >= {:.3}",
                    idx + 1,
                    tip,
                    score_hint
                )
            })
            .collect()
    }

    async fn propose_candidate_instructions(
        &self,
        program_description: &str,
        output_hint: &str,
        num_candidates: usize,
    ) -> Result<Vec<String>> {
        crate::optimizer::propose::propose_instructions_with_hint(
            program_description,
            output_hint,
            num_candidates,
            None,
        )
        .await
    }

    pub fn create_prompt_candidates(&self, instructions: Vec<String>) -> Vec<PromptCandidate> {
        instructions.into_iter().map(PromptCandidate::new).collect()
    }

    async fn evaluate_candidate<S, M, MT>(
        &self,
        module: &mut M,
        candidate: &PromptCandidate,
        eval_examples: &[Example<S>],
        predictor_name: &str,
        metric: &MT,
    ) -> Result<f32>
    where
        S: Signature,
        S::Input: Clone,
        M: Module<Input = S::Input> + for<'a> Facet<'a>,
        MT: TypedMetric<S, M>,
    {
        let original_state = with_named_predictor(module, predictor_name, |predictor| {
            Ok(predictor.dump_state())
        })?;

        with_named_predictor(module, predictor_name, |predictor| {
            predictor.set_instruction(candidate.instruction.clone());
            // TODO(trace-demos): derive per-predictor demos from successful traces.
            // MIPRO is intentionally instruction-only in this release.
            Ok(())
        })?;

        let minibatch_end = eval_examples.len().min(self.minibatch_size);
        let minibatch = &eval_examples[..minibatch_end];
        let evaluation = evaluate_module_with_metric(&*module, minibatch, metric).await;

        match evaluation {
            Ok(outcomes) => {
                with_named_predictor(module, predictor_name, |predictor| {
                    predictor.load_state(original_state.clone())
                })?;
                Ok(average_score(&outcomes))
            }
            Err(eval_err) => {
                if let Err(restore_err) =
                    with_named_predictor(module, predictor_name, |predictor| {
                        predictor.load_state(original_state)
                    })
                {
                    return Err(anyhow!(
                        "candidate evaluation failed: {eval_err}; failed to restore predictor state: {restore_err}"
                    ));
                }
                Err(eval_err)
            }
        }
    }

    async fn evaluate_and_select_best<S, M, MT>(
        &self,
        module: &mut M,
        candidates: Vec<PromptCandidate>,
        eval_examples: &[Example<S>],
        predictor_name: &str,
        metric: &MT,
    ) -> Result<PromptCandidate>
    where
        S: Signature,
        S::Input: Clone,
        M: Module<Input = S::Input> + for<'a> Facet<'a>,
        MT: TypedMetric<S, M>,
    {
        let mut evaluated = Vec::new();

        let num_trials = self.num_trials.max(1);
        for candidate in candidates.into_iter().take(num_trials) {
            let score = self
                .evaluate_candidate::<S, _, _>(
                    module,
                    &candidate,
                    eval_examples,
                    predictor_name,
                    metric,
                )
                .await?;
            evaluated.push(candidate.with_score(score));
        }

        evaluated
            .into_iter()
            .max_by(|a, b| {
                a.score
                    .partial_cmp(&b.score)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .ok_or_else(|| anyhow!("no candidates to evaluate"))
    }

    pub fn format_schema_fields(&self, signature: &SignatureSchema) -> String {
        let mut result = String::new();

        result.push_str("Input Fields:\n");
        for field in signature.input_fields() {
            let desc = if field.docs.is_empty() {
                "No description"
            } else {
                field.docs.as_str()
            };
            result.push_str(&format!("  - {}: {}\n", field.lm_name, desc));
        }

        result.push_str("\nOutput Fields:\n");
        for field in signature.output_fields() {
            let desc = if field.docs.is_empty() {
                "No description"
            } else {
                field.docs.as_str()
            };
            result.push_str(&format!("  - {}: {}\n", field.lm_name, desc));
        }

        result
    }
}

impl Optimizer for MIPROv2 {
    type Report = ();

    async fn compile<S, M, MT>(
        &self,
        module: &mut M,
        trainset: Vec<Example<S>>,
        metric: &MT,
    ) -> Result<Self::Report>
    where
        S: Signature,
        S::Input: Clone,
        M: Module<Input = S::Input> + for<'a> Facet<'a>,
        MT: TypedMetric<S, M>,
    {
        let predictor_names = predictor_names(module)?;

        if predictor_names.is_empty() {
            return Err(anyhow!("no optimizable predictors found"));
        }

        for predictor_name in predictor_names {
            let signature_desc = {
                with_named_predictor(module, &predictor_name, |predictor| {
                    Ok(self.format_schema_fields(predictor.schema()))
                })?
            };

            let traces = self
                .generate_traces::<S, _, _>(module, &trainset, metric)
                .await?;
            let output_hint = with_named_predictor(module, &predictor_name, |predictor| {
                Ok(predictor
                    .schema()
                    .output_fields()
                    .iter()
                    .map(|f| f.lm_name.to_string())
                    .collect::<Vec<_>>()
                    .join(", "))
            })?;
            let mut instructions = self
                .propose_candidate_instructions(&signature_desc, &output_hint, self.num_candidates)
                .await?;
            if instructions.len() < self.num_candidates {
                // Blend in tip-based variants from traces when LM returns few candidates.
                let extras = self.generate_candidate_instructions(
                    &signature_desc,
                    &traces,
                    self.num_candidates,
                );
                for extra in extras {
                    if instructions.len() >= self.num_candidates {
                        break;
                    }
                    if !instructions.iter().any(|i| i == &extra) {
                        instructions.push(extra);
                    }
                }
            }
            let candidates = self.create_prompt_candidates(instructions);
            let best_candidate = self
                .evaluate_and_select_best::<S, _, _>(
                    module,
                    candidates,
                    &trainset,
                    &predictor_name,
                    metric,
                )
                .await?;

            with_named_predictor(module, &predictor_name, |predictor| {
                predictor.set_instruction(best_candidate.instruction.clone());
                // TODO(trace-demos): apply per-predictor demos derived from traces.
                // MIPRO is intentionally instruction-only in this release.
                Ok(())
            })?;
        }

        Ok(())
    }
}

/// Dynamic execution trace used by [`MIPROv2::compile_dyn`].
#[derive(Clone, Debug)]
pub struct DynTrace {
    pub input: crate::data::example::Example,
    pub output: crate::data::example::Example,
    pub score: Option<f32>,
}

impl MIPROv2 {
    /// Dynamic MIPRO: instruction search + demo seeding from successful traces.
    pub async fn compile_dyn<M, MT>(
        &self,
        module: &mut M,
        trainset: Vec<crate::data::example::Example>,
        metric: &MT,
    ) -> Result<()>
    where
        M: crate::predictors::DynModule + for<'a> Facet<'a>,
        MT: crate::evaluate::DynMetric,
    {
        use crate::evaluate::input_only;
        use crate::optimizer::dyn_compile::{
            assign_demos_best_effort, ensure_predictors, score_instruction_dyn,
        };

        let predictor_names = ensure_predictors(module)?;
        for predictor_name in predictor_names {
            let signature_desc = with_named_predictor(module, &predictor_name, |predictor| {
                Ok(self.format_schema_fields(predictor.schema()))
            })?;

            let mut traces = Vec::new();
            let mut successful_demos = Vec::new();
            for example in &trainset {
                let predicted = module
                    .call(input_only(example))
                    .await
                    .map_err(|err| anyhow!("{err}"))?;
                let outcome = metric.evaluate(example, &predicted).await?;
                traces.push(DynTrace {
                    input: input_only(example),
                    output: predicted.into_inner(),
                    score: Some(outcome.score),
                });
                if outcome.score >= 1.0 || outcome.score >= 0.99 {
                    successful_demos.push(example.clone());
                }
            }

            let output_hint = with_named_predictor(module, &predictor_name, |predictor| {
                Ok(predictor
                    .schema()
                    .output_fields()
                    .iter()
                    .map(|f| f.lm_name.to_string())
                    .collect::<Vec<_>>()
                    .join(", "))
            })?;
            let mut instructions = self
                .propose_candidate_instructions(&signature_desc, &output_hint, self.num_candidates)
                .await?;
            if instructions.len() < self.num_candidates {
                let tips = PromptingTips::default_tips();
                let score_hint = traces.iter().filter_map(|t| t.score).fold(0.0f32, f32::max);
                for (idx, tip) in tips.tips.iter().enumerate() {
                    if instructions.len() >= self.num_candidates {
                        break;
                    }
                    instructions.push(format!(
                        "{signature_desc}\n\nOptimization candidate {}:\n- {tip}\n- Target score >= {score_hint:.3}",
                        idx + 1
                    ));
                }
            }

            let mut best_instruction = instructions
                .first()
                .cloned()
                .unwrap_or_else(|| "Answer carefully.".into());
            let mut best_score = f32::MIN;
            for candidate in instructions.into_iter().take(self.num_trials.max(1)) {
                let score =
                    score_instruction_dyn(module, &predictor_name, &candidate, &trainset, metric)
                        .await?;
                if score > best_score {
                    best_score = score;
                    best_instruction = candidate;
                }
            }

            with_named_predictor(module, &predictor_name, |predictor| {
                predictor.set_instruction(best_instruction);
                if !successful_demos.is_empty() {
                    let demos = successful_demos
                        .iter()
                        .take(self.minibatch_size.max(1))
                        .cloned()
                        .collect::<Vec<_>>();
                    let _ = assign_demos_best_effort(predictor, demos);
                }
                Ok(())
            })?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use anyhow::{Result, anyhow};

    use super::*;
    use crate::evaluate::{MetricOutcome, TypedMetric};
    use crate::{CallMetadata, Predict, PredictError, Predicted, Signature};

    #[derive(Signature, Clone, Debug)]
    struct MiproStateSig {
        #[input]
        prompt: String,

        #[output]
        answer: String,
    }

    #[derive(facet::Facet)]
    #[facet(crate = facet)]
    struct MiproStateModule {
        predictor: Predict<MiproStateSig>,
    }

    impl Module for MiproStateModule {
        type Input = MiproStateSigInput;
        type Output = MiproStateSigOutput;

        async fn forward(
            &self,
            input: MiproStateSigInput,
        ) -> Result<Predicted<MiproStateSigOutput>, PredictError> {
            Ok(Predicted::new(
                MiproStateSigOutput {
                    answer: input.prompt,
                },
                CallMetadata::default(),
            ))
        }
    }

    struct AlwaysFailMetric;

    impl TypedMetric<MiproStateSig, MiproStateModule> for AlwaysFailMetric {
        async fn evaluate(
            &self,
            _example: &Example<MiproStateSig>,
            _prediction: &Predicted<MiproStateSigOutput>,
        ) -> Result<MetricOutcome> {
            Err(anyhow!("metric failure"))
        }
    }

    fn trainset() -> Vec<Example<MiproStateSig>> {
        vec![Example::new(
            MiproStateSigInput {
                prompt: "one".to_string(),
            },
            MiproStateSigOutput {
                answer: "one".to_string(),
            },
        )]
    }

    #[tokio::test]
    async fn evaluate_candidate_restores_state_when_metric_errors() {
        let optimizer = MIPROv2::builder()
            .num_candidates(2)
            .num_trials(1)
            .minibatch_size(1)
            .build();
        let mut module = MiproStateModule {
            predictor: Predict::<MiproStateSig>::builder()
                .instruction("seed-instruction")
                .build(),
        };
        let candidate = PromptCandidate::new("candidate instruction".to_string());

        let err = optimizer
            .evaluate_candidate::<MiproStateSig, _, _>(
                &mut module,
                &candidate,
                &trainset(),
                "predictor",
                &AlwaysFailMetric,
            )
            .await
            .expect_err("candidate evaluation should propagate metric failure");
        assert!(err.to_string().contains("metric failure"));

        let instruction = with_named_predictor(&mut module, "predictor", |predictor| {
            Ok(predictor.instruction())
        })
        .expect("predictor lookup should succeed");
        assert_eq!(instruction, "seed-instruction");
    }
}