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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
use anyhow::Result;
use bamltype::baml_types::BamlMap;
use rig::tool::ToolDyn;
use serde_json::Value;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::ops::ControlFlow;
use std::sync::Arc;
use tracing::{debug, trace};

use crate as dsrs;
use crate::core::{DynPredictor, Module, PredictAccessorFns, PredictState, Signature};
use crate::data::example::Example as RawExample;
use crate::{
    BamlType, BamlValue, CallMetadata, Chat, GLOBAL_SETTINGS, LmError, LmUsage,
    PredictError, Predicted, Prediction, SignatureSchema,
};

/// A typed input/output pair for few-shot prompting.
///
/// Demos are formatted as user/assistant exchanges in the prompt, showing the LM
/// what good responses look like. The types enforce that demos match the signature —
/// you can't accidentally pass a `QAOutput` demo to a `Predict<SummarizeSig>`.
///
/// ```
/// use dsir::*;
/// use dsir::doctest::*;
///
/// let example = Example::<QA>::new(
///     QAInput { question: "What is 2+2?".into() },
///     QAOutput { answer: "4".into() },
/// );
/// ```
#[derive(Clone, Debug, facet::Facet)]
#[facet(crate = facet)]
pub struct Example<S: Signature> {
    pub input: S::Input,
    pub output: S::Output,
}

impl<S: Signature> Example<S> {
    pub fn new(input: S::Input, output: S::Output) -> Self {
        Self { input, output }
    }
}

fn predict_dyn_visit<S>(
    value: *mut (),
    visitor: &mut dyn FnMut(&mut dyn DynPredictor) -> ControlFlow<()>,
) -> ControlFlow<()>
where
    S: Signature,
{
    // SAFETY: this function is only called through the shape-local
    // `dsrs::predict_accessor` payload attached to a shape with strict
    // `Predict` identity (`type_identifier` + `module_path`).
    let typed = unsafe { &mut *(value.cast::<Predict<S>>()) };
    visitor(typed)
}

type VisitPredictorMutFn =
    fn(*mut (), &mut dyn FnMut(&mut dyn DynPredictor) -> ControlFlow<()>) -> ControlFlow<()>;

trait PredictAccessorProvider {
    const VISIT_MUT: VisitPredictorMutFn;
}

impl<S> PredictAccessorProvider for S
where
    S: Signature,
{
    const VISIT_MUT: VisitPredictorMutFn = predict_dyn_visit::<S>;
}

/// The leaf module. The only thing in the system that actually calls the LM.
///
/// One `Predict` = one prompt template = one LM call. It takes a [`Signature`]'s fields
/// and instruction, formats them into a prompt (with any demos and tools), calls the
/// configured LM, and parses the response back into `S::Output`. Every other module —
/// [`ChainOfThought`](crate::ChainOfThought), `ReAct`, custom pipelines — ultimately
/// delegates to one or more `Predict` leaves.
///
/// This is also the unit of optimization. When an optimizer tunes your program, it's
/// adjusting `Predict` leaves: their demos (few-shot examples) and instructions.
/// The optimizer's Facet walker discovers leaves automatically from struct fields —
/// no `#[parameter]` annotations or manual traversal needed.
///
/// # Optimizer discovery
///
/// `Predict<S>` encodes shape-local discovery payloads:
/// - strict shape identity (`type_identifier` + `module_path`) identifies the leaf
/// - `dsrs::predict_accessor` stores the typed mutable accessor visitor
///
/// The optimizer walker consumes these through `visit_named_predictors_mut`.
/// There is no runtime registration side effect in `new()` or `build()`.
///
/// ```no_run
/// # async fn example() -> Result<(), dsir::PredictError> {
/// use dsir::*;
/// use dsir::doctest::*;
///
/// // Minimal
/// let predict = Predict::<QA>::new();
/// let result = predict.call(QAInput { question: "What is 2+2?".into() }).await?;
/// println!("{}", result.answer);
///
/// // With demos and custom instruction
/// let predict = Predict::<QA>::builder()
///     .demo(Example::new(
///         QAInput { question: "What is 1+1?".into() },
///         QAOutput { answer: "2".into() },
///     ))
///     .instruction("Answer in one word.")
///     .build();
/// # Ok(())
/// # }
/// ```
#[derive(facet::Facet)]
#[facet(crate = facet, opaque)]
#[facet(dsrs::predict_accessor = &PredictAccessorFns {
    visit_mut: <S as PredictAccessorProvider>::VISIT_MUT,
})]
pub struct Predict<S: Signature> {
    #[facet(skip, opaque)]
    tools: Vec<Arc<dyn ToolDyn>>,
    #[facet(skip, opaque)]
    demos: Vec<Example<S>>,
    instruction_override: Option<String>,
    #[facet(skip, opaque)]
    lm: Option<Arc<crate::core::LM>>,
    #[facet(skip, opaque)]
    _marker: PhantomData<S>,
}

impl<S: Signature> Predict<S> {
    /// Creates a new `Predict` with no demos, no instruction override, and no tools.
    pub fn new() -> Self {
        Self {
            tools: Vec::new(),
            demos: Vec::new(),
            instruction_override: None,
            lm: None,
            _marker: PhantomData,
        }
    }

    /// Returns a builder for configuring demos, instruction, and tools.
    pub fn builder() -> PredictBuilder<S> {
        PredictBuilder::new()
    }

    /// Calls the LM with this predictor's signature, demos, and tools.
    ///
    /// Delegates to [`forward`](Predict::forward). Both exist for symmetry with the
    /// [`Module`] trait; `call` is what you use, `forward` is the implementation.
    #[tracing::instrument(
        name = "dsrs.predict.call",
        level = "debug",
        skip(self, input),
        fields(
            signature = std::any::type_name::<S>(),
            demo_count = self.demos.len(),
            tool_count = self.tools.len(),
            instruction_override = self.instruction_override.is_some(),
            tracing_graph = crate::trace::is_tracing()
        )
    )]
    pub async fn call(&self, input: S::Input) -> Result<Predicted<S::Output>, PredictError>
    where
        S::Input: BamlType,
        S::Output: BamlType,
    {
        self.forward(input).await
    }

    /// Builds the prompt, calls the LM, and parses the response.
    ///
    /// The full pipeline:
    /// 1. Format system message from the signature's schema and instruction override
    /// 2. Format demo examples as user/assistant exchanges
    /// 3. Format the input as the final user message
    /// 4. Call the LM (with any tools attached)
    /// 5. Parse the response into `S::Output` via the `[[ ## field ## ]]` protocol
    /// 6. Record a trace node if inside a [`trace()`](crate::trace::trace) scope
    ///
    /// # Errors
    ///
    /// - [`PredictError::Lm`] if the LM call fails (network, rate limit, timeout)
    /// - [`PredictError::Parse`] if the response can't be parsed into the output fields
    pub async fn forward(&self, input: S::Input) -> Result<Predicted<S::Output>, PredictError>
    where
        S::Input: BamlType,
        S::Output: BamlType,
    {
        let chat = self.build_chat(&input)?;
        let (predicted, _) = self.call_and_parse(chat).await?;
        Ok(predicted)
    }

    /// Continues a prior conversation and parses the LM's response.
    ///
    /// The caller owns the `Chat` between calls:
    /// 1. Call [`forward`] to get the first turn's `(Predicted, Chat)`.
    /// 2. Append a follow-up user message to the returned `Chat`.
    /// 3. Call `forward_continue` with the updated `Chat`.
    ///
    /// The LM response is parsed using the same `[[ ## field ## ]]` protocol.
    /// The caller is responsible for including format instructions in follow-up
    /// messages if the model needs reminding of the output format.
    pub async fn forward_continue(
        &self,
        chat: Chat,
    ) -> Result<(Predicted<S::Output>, Chat), PredictError>
    where
        S::Input: BamlType,
        S::Output: BamlType,
    {
        trace!(message_count = chat.len(), "continuing prior chat");
        self.call_and_parse(chat).await
    }

    /// Builds the first-turn chat from the signature, demos, and input.
    ///
    /// Returns a [`Chat`] ready to pass to [`call_and_parse`](Predict::call_and_parse)
    /// or [`forward_continue`](Predict::forward_continue). Useful when you need to
    /// inspect or modify the prompt before sending it to the LM.
    #[allow(clippy::result_large_err)]
    pub fn build_chat(&self, input: &S::Input) -> Result<Chat, PredictError>
    where
        S::Input: BamlType,
    {
        let chat_adapter = crate::core::settings::chat_adapter();
        let system = match chat_adapter
            .format_system_message_typed_with_instruction::<S>(self.instruction_override.as_deref())
        {
            Ok(system) => system,
            Err(err) => {
                return Err(PredictError::Lm {
                    source: LmError::Provider {
                        provider: "internal".to_string(),
                        message: err.to_string(),
                        source: None,
                    },
                });
            }
        };

        let user = chat_adapter.format_user_message_typed::<S>(input);
        trace!(
            system_len = system.len(),
            user_len = user.len(),
            "typed prompt formatted"
        );

        let mut chat = Chat::new(vec![]);
        chat.push("system", &system);
        for demo in &self.demos {
            let demo_user = chat_adapter.format_user_message_typed::<S>(&demo.input);
            let demo_assistant = chat_adapter.format_assistant_message_typed::<S>(&demo.output);
            chat.push("user", &demo_user);
            chat.push("assistant", &demo_assistant);
        }
        chat.push("user", &user);
        trace!(message_count = chat.len(), "chat constructed");
        Ok(chat)
    }

    /// Calls the LM with the given chat and parses the response.
    ///
    /// This is the shared implementation behind [`forward`](Predict::forward) and
    /// [`forward_continue`](Predict::forward_continue). Use it directly when you need
    /// both the prediction and the updated conversation history.
    pub async fn call_and_parse(
        &self,
        chat: Chat,
    ) -> Result<(Predicted<S::Output>, Chat), PredictError>
    where
        S::Input: BamlType,
        S::Output: BamlType,
    {
        let lm = match &self.lm {
            Some(lm) => Arc::clone(lm),
            None => {
                let guard = GLOBAL_SETTINGS.read().unwrap();
                let settings = guard.as_ref().unwrap();
                Arc::clone(&settings.lm)
            }
        };

        let response = match lm.call(chat, self.tools.clone()).await {
            Ok(response) => response,
            Err(err) => {
                return Err(PredictError::Lm {
                    source: LmError::Provider {
                        provider: lm.model.clone(),
                        message: err.to_string(),
                        source: None,
                    },
                });
            }
        };
        debug!(
            prompt_tokens = response.usage.prompt_tokens,
            completion_tokens = response.usage.completion_tokens,
            total_tokens = response.usage.total_tokens,
            tool_calls = response.tool_calls.len(),
            "lm response received"
        );

        let crate::core::lm::LMResponse {
            output,
            usage,
            chat,
            tool_calls,
            tool_executions,
        } = response;

        let node_id = if crate::trace::is_tracing() {
            crate::trace::record_node(
                crate::trace::NodeType::Predict {
                    signature_name: std::any::type_name::<S>().to_string(),
                },
                vec![],
                None,
            )
        } else {
            None
        };

        let chat_adapter = crate::core::settings::chat_adapter();
        let raw_response = output.content().to_string();
        let lm_usage = usage.clone();

        let (typed_output, field_metas) = match chat_adapter.parse_response_typed::<S>(&output) {
            Ok(parsed) => parsed,
            Err(err) => {
                let failed_fields = err.fields();
                debug!(
                    failed_fields = failed_fields.len(),
                    fields = ?failed_fields,
                    raw_response_len = raw_response.len(),
                    "typed parse failed"
                );
                return Err(PredictError::Parse {
                    source: err,
                    raw_response,
                    lm_usage,
                });
            }
        };

        let checks_total = field_metas
            .values()
            .map(|meta| meta.checks.len())
            .sum::<usize>();
        let checks_failed = field_metas
            .values()
            .flat_map(|meta| meta.checks.iter())
            .filter(|check| !check.passed)
            .count();
        let flagged_fields = field_metas
            .values()
            .filter(|meta| !meta.flags.is_empty())
            .count();
        debug!(
            output_fields = field_metas.len(),
            checks_total, checks_failed, flagged_fields, "typed parse completed"
        );

        if let Some(id) = node_id {
            match prediction_from_output::<S>(&typed_output, lm_usage.clone(), Some(id)) {
                Ok(prediction) => {
                    crate::trace::record_output(id, prediction);
                    trace!(node_id = id, "recorded typed predictor output");
                }
                Err(err) => {
                    debug!(error = %err, "failed to build typed prediction for trace output");
                }
            }
        }

        let metadata = CallMetadata::new(
            raw_response,
            lm_usage,
            tool_calls,
            tool_executions,
            node_id,
            field_metas,
        );

        Ok((Predicted::new(typed_output, metadata), chat))
    }
}

impl<S: Signature> Default for Predict<S> {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for [`Predict`] with demos, tools, and instruction override.
///
/// ```ignore
/// let predict = Predict::<QA>::builder()
///     .demo(demo1)
///     .demo(demo2)
///     .instruction("Answer in one word.")
///     .add_tool(my_tool)
///     .build();
/// ```
pub struct PredictBuilder<S: Signature> {
    tools: Vec<Arc<dyn ToolDyn>>,
    demos: Vec<Example<S>>,
    instruction_override: Option<String>,
    lm: Option<Arc<crate::core::LM>>,
    _marker: PhantomData<S>,
}

impl<S: Signature> PredictBuilder<S> {
    fn new() -> Self {
        Self {
            tools: Vec::new(),
            demos: Vec::new(),
            instruction_override: None,
            lm: None,
            _marker: PhantomData,
        }
    }

    /// Adds a single demo (few-shot example) to the predictor.
    pub fn demo(mut self, demo: Example<S>) -> Self {
        self.demos.push(demo);
        self
    }

    /// Adds multiple demos from an iterator.
    pub fn with_demos(mut self, demos: impl IntoIterator<Item = Example<S>>) -> Self {
        self.demos.extend(demos);
        self
    }

    /// Adds a tool the LM can invoke during this call.
    pub fn add_tool(mut self, tool: impl ToolDyn + 'static) -> Self {
        self.tools.push(Arc::new(tool));
        self
    }

    /// Adds multiple tools from an iterator.
    pub fn with_tools(mut self, tools: impl IntoIterator<Item = Arc<dyn ToolDyn>>) -> Self {
        self.tools.extend(tools);
        self
    }

    /// Overrides the signature's default instruction for this predictor.
    pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
        self.instruction_override = Some(instruction.into());
        self
    }

    /// Sets a per-instance LM for this predictor, bypassing the global.
    ///
    /// When set, this `Predict` will use the given LM instead of the one
    /// configured via [`configure()`](crate::configure). This enables
    /// concurrent calls with different models — each `Predict` leaf can
    /// target a different provider without contention on the global setting.
    ///
    /// ```ignore
    /// let predict = Predict::<QA>::builder()
    ///     .lm(LM::builder().model("anthropic:claude-sonnet-4-20250514").build().await?)
    ///     .build();
    /// ```
    pub fn lm(mut self, lm: crate::core::LM) -> Self {
        self.lm = Some(Arc::new(lm));
        self
    }

    /// Builds the [`Predict`].
    pub fn build(self) -> Predict<S> {
        Predict {
            tools: self.tools,
            demos: self.demos,
            instruction_override: self.instruction_override,
            lm: self.lm,
            _marker: PhantomData,
        }
    }
}

fn baml_map_from_example_keys(
    data: &HashMap<String, Value>,
    keys: &[String],
) -> Result<BamlMap<String, BamlValue>> {
    let mut map = BamlMap::new();
    for key in keys {
        if let Some(value) = data.get(key) {
            let baml_value =
                BamlValue::try_from(value.clone()).map_err(|err| anyhow::anyhow!(err))?;
            map.insert(key.clone(), baml_value);
        }
    }
    Ok(map)
}

fn input_keys_for_signature<S: Signature>(example: &RawExample) -> Vec<String> {
    if example.input_keys.is_empty() {
        S::schema()
            .input_fields()
            .iter()
            .map(|field| field.rust_name.clone())
            .collect()
    } else {
        example.input_keys.clone()
    }
}

fn output_keys_for_signature<S: Signature>(example: &RawExample) -> Vec<String> {
    if example.output_keys.is_empty() {
        S::schema()
            .output_fields()
            .iter()
            .map(|field| field.rust_name.clone())
            .collect()
    } else {
        example.output_keys.clone()
    }
}

fn input_from_raw_example<S: Signature>(example: &RawExample) -> Result<S::Input>
where
    S::Input: BamlType,
{
    let keys = input_keys_for_signature::<S>(example);
    let map = baml_map_from_example_keys(&example.data, &keys)?;
    let baml_value = BamlValue::Map(map);
    S::Input::try_from_baml_value(baml_value).map_err(|err| anyhow::anyhow!(err))
}

fn output_from_raw_example<S: Signature>(example: &RawExample) -> Result<S::Output>
where
    S::Output: BamlType,
{
    let keys = output_keys_for_signature::<S>(example);
    let map = baml_map_from_example_keys(&example.data, &keys)?;
    let baml_value = BamlValue::Map(map);
    S::Output::try_from_baml_value(baml_value).map_err(|err| anyhow::anyhow!(err))
}

fn typed_example_from_raw<S: Signature>(example: RawExample) -> Result<Example<S>>
where
    S::Input: BamlType,
    S::Output: BamlType,
{
    let input = input_from_raw_example::<S>(&example)?;
    let output = output_from_raw_example::<S>(&example)?;
    Ok(Example::new(input, output))
}

fn raw_example_from_typed<S: Signature>(example: &Example<S>) -> Result<RawExample>
where
    S::Input: BamlType,
    S::Output: BamlType,
{
    let input_value = serde_json::to_value(example.input.to_baml_value())?;
    let output_value = serde_json::to_value(example.output.to_baml_value())?;

    let input_map = input_value
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("expected object for signature input"))?
        .clone();
    let output_map = output_value
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("expected object for signature output"))?
        .clone();

    let input_keys = input_map.keys().cloned().collect();
    let output_keys = output_map.keys().cloned().collect();

    let mut data = HashMap::new();
    data.extend(input_map);
    data.extend(output_map);

    Ok(RawExample::new(data, input_keys, output_keys))
}

fn prediction_from_output<S: Signature>(
    output: &S::Output,
    lm_usage: LmUsage,
    node_id: Option<usize>,
) -> Result<Prediction>
where
    S::Output: BamlType,
{
    let output_value = serde_json::to_value(output.to_baml_value())?;
    let output_map = output_value
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("expected object for signature output"))?;

    let data = output_map
        .iter()
        .map(|(key, value)| (key.clone(), value.clone()))
        .collect::<HashMap<String, Value>>();
    let mut prediction = Prediction::new(data, lm_usage);
    prediction.node_id = node_id;
    Ok(prediction)
}

impl<S> Module for Predict<S>
where
    S: Signature + Clone,
    S::Input: BamlType,
    S::Output: BamlType,
{
    type Input = S::Input;
    type Output = S::Output;

    #[tracing::instrument(
        name = "dsrs.module.forward",
        level = "debug",
        skip(self, input),
        fields(
            signature = std::any::type_name::<S>(),
            typed = true
        )
    )]
    async fn forward(&self, input: S::Input) -> Result<Predicted<S::Output>, PredictError> {
        Predict::forward(self, input).await
    }
}

impl<S> DynPredictor for Predict<S>
where
    S: Signature,
    S::Input: BamlType,
    S::Output: BamlType,
{
    fn schema(&self) -> &SignatureSchema {
        S::schema()
    }

    fn instruction(&self) -> String {
        self.instruction_override
            .clone()
            .unwrap_or_else(|| S::instruction().to_string())
    }

    fn set_instruction(&mut self, instruction: String) {
        self.instruction_override = Some(instruction);
    }

    fn demos_as_examples(&self) -> Vec<RawExample> {
        self.demos
            .iter()
            .map(|example| {
                raw_example_from_typed::<S>(example)
                    .expect("typed Predict demo conversion should succeed")
            })
            .collect()
    }

    fn set_demos_from_examples(&mut self, demos: Vec<RawExample>) -> Result<()> {
        self.demos = demos
            .into_iter()
            .map(typed_example_from_raw::<S>)
            .collect::<Result<Vec<_>>>()?;
        Ok(())
    }

    fn dump_state(&self) -> PredictState {
        PredictState {
            demos: self.demos_as_examples(),
            instruction_override: self.instruction_override.clone(),
        }
    }

    fn load_state(&mut self, state: PredictState) -> Result<()> {
        self.set_demos_from_examples(state.demos)?;
        self.instruction_override = state.instruction_override;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

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

        #[output]
        answer: String,
    }

    fn typed_row(prompt: &str, answer: &str) -> Example<PredictConversionSig> {
        Example::new(
            PredictConversionSigInput {
                prompt: prompt.to_string(),
            },
            PredictConversionSigOutput {
                answer: answer.to_string(),
            },
        )
    }

    #[test]
    fn typed_and_raw_example_round_trip_preserves_fields() {
        let typed = typed_row("question", "response");
        let raw = raw_example_from_typed::<PredictConversionSig>(&typed)
            .expect("typed example should convert to raw example");

        assert_eq!(raw.input_keys, vec!["prompt".to_string()]);
        assert_eq!(raw.output_keys, vec!["answer".to_string()]);
        assert_eq!(raw.data.get("prompt"), Some(&json!("question")));
        assert_eq!(raw.data.get("answer"), Some(&json!("response")));

        let round_trip = typed_example_from_raw::<PredictConversionSig>(raw)
            .expect("raw example should convert back to typed example");
        assert_eq!(round_trip.input.prompt, "question");
        assert_eq!(round_trip.output.answer, "response");
    }

    #[test]
    fn typed_example_from_raw_uses_schema_keys_when_key_lists_missing() {
        let raw = RawExample::new(
            HashMap::from([
                ("prompt".to_string(), json!("schema-input")),
                ("answer".to_string(), json!("schema-output")),
            ]),
            Vec::new(),
            Vec::new(),
        );

        let typed = typed_example_from_raw::<PredictConversionSig>(raw)
            .expect("schema key fallback should parse typed example");
        assert_eq!(typed.input.prompt, "schema-input");
        assert_eq!(typed.output.answer, "schema-output");
    }

    #[test]
    fn dyn_predictor_set_demos_from_examples_round_trips_raw_rows() {
        let typed = typed_row("demo-input", "demo-output");
        let raw = raw_example_from_typed::<PredictConversionSig>(&typed)
            .expect("typed demo should convert to raw demo");
        let mut predictor = Predict::<PredictConversionSig>::new();

        DynPredictor::set_demos_from_examples(&mut predictor, vec![raw])
            .expect("predictor should accept raw demos");

        let demos = DynPredictor::demos_as_examples(&predictor);
        assert_eq!(demos.len(), 1);
        assert_eq!(demos[0].data.get("prompt"), Some(&json!("demo-input")));
        assert_eq!(demos[0].data.get("answer"), Some(&json!("demo-output")));
    }
}