dspy-rs 0.7.3

A DSPy rewrite(not port) to 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
use schemars::JsonSchema;
use std::sync::Arc;
use tokio::sync::Mutex;

use dspy_rs::{
    Cache, Chat, ChatAdapter, DummyLM, Example, Message, MetaSignature, Signature,
    adapter::Adapter, example, hashmap, sign,
};

#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_chat_adapter() {
    let signature = sign! {
        (problem: String) -> answer: String
    };

    let lm = DummyLM::default();
    let adapter = ChatAdapter;

    let messages: Chat = adapter.format(
        &signature,
        Example::new(
            hashmap! {
                "problem".to_string() => "What is the capital of France?".to_string().into(),
                "answer".to_string() => "Paris".to_string().into(),
            },
            vec!["problem".to_string()],
            vec!["answer".to_string()],
        ),
    );

    let json_value = messages.to_json();
    let json = json_value.as_array().unwrap();

    assert_eq!(messages.len(), 2);
    assert_eq!(json[0]["role"], "system");
    assert_eq!(json[1]["role"], "user");

    assert_eq!(
        json[0]["content"],
        "Your input fields are:\n1. `problem` (String)\n\nYour output fields are:\n1. `answer` (String)\n\nAll interactions will be structured in the following way, with the appropriate values filled in.\n\n[[ ## problem ## ]]\nproblem\n\n[[ ## answer ## ]]\nanswer\n\n[[ ## completed ## ]]\n\nIn adhering to this structure, your objective is:\n\tGiven the fields `problem`, produce the fields `answer`."
    );
    assert_eq!(
        json[1]["content"],
        "[[ ## problem ## ]]\nWhat is the capital of France?\n\nRespond with the corresponding output fields, starting with the field `answer`, and then ending with the marker for `completed`.".to_string()
    );

    let test_example = example! {
        "problem": "input" => "What is the capital of France?",
        "answer": "output" => "Paris"
    };
    let response = lm
        .call(
            test_example,
            Chat::new(vec![
                Message::system("You are a helpful assistant."),
                Message::user("Hello, world!"),
            ]),
            "[[ ## answer ## ]]\n150 degrees\n\n[[ ## completed ## ]]".to_string(),
        )
        .await
        .unwrap();
    let output = adapter.parse_response(&signature, response.output);

    assert_eq!(output.len(), 1);
    assert_eq!(output.get("answer").unwrap(), "150 degrees");
}

#[allow(dead_code)]
#[Signature(cot, hint)]
struct TestSignature {
    ///You are a helpful assistant that can answer questions. You will be given a problem and a hint. You will need to use the hint to answer the problem. You will then need to provide the reasoning and the answer.

    #[input]
    pub problem: String,
    #[output]
    pub answer: String,
}

#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_chat_adapter_with_multiple_fields() {
    let signature = TestSignature::new();

    let lm = DummyLM::default();
    let adapter = ChatAdapter;

    let messages: Chat = adapter.format(
        &signature,
        Example::new(
            hashmap! {
                "problem".to_string() => "What is the capital of France?".to_string().into(),
                "hint".to_string() => "The capital of France is Paris.".to_string().into(),
            },
            vec!["problem".to_string(), "hint".to_string()],
            vec!["reasoning".to_string(), "answer".to_string()],
        ),
    );

    let json_value = messages.to_json();
    let json = json_value.as_array().unwrap();

    assert_eq!(messages.len(), 2);
    assert_eq!(json[0]["role"], "system");
    assert_eq!(json[1]["role"], "user");

    assert_eq!(
        json[0]["content"],
        "Your input fields are:\n1. `problem` (String)\n2. `hint` (String): Hint for the query\n\nYour output fields are:\n1. `reasoning` (String): Think step by step\n2. `answer` (String)\n\nAll interactions will be structured in the following way, with the appropriate values filled in.\n\n[[ ## problem ## ]]\nproblem\n\n[[ ## hint ## ]]\nhint\n\n[[ ## reasoning ## ]]\nreasoning\n\n[[ ## answer ## ]]\nanswer\n\n[[ ## completed ## ]]\n\nIn adhering to this structure, your objective is:\n\tYou are a helpful assistant that can answer questions. You will be given a problem and a hint. You will need to use the hint to answer the problem. You will then need to provide the reasoning and the answer.".to_string()
    );
    assert_eq!(
        json[1]["content"],
        "[[ ## problem ## ]]\nWhat is the capital of France?\n\n[[ ## hint ## ]]\nThe capital of France is Paris.\n\nRespond with the corresponding output fields, starting with the field `reasoning`, then `answer`, and then ending with the marker for `completed`."
    );

    let test_example = example! {
        "problem": "input" => "What is the capital of France?",
        "hint": "output" => "The capital of France is Paris.",
        "reasoning": "output" => "The capital of France is Paris.",
        "answer": "output" => "Paris"
    };

    let response = lm
        .call(
            test_example,
            Chat::new(vec![
                Message::system("You are a helpful assistant."),
                Message::user("Hello, world!"),
            ]),
            "[[ ## reasoning ## ]]\nThe capital of France is Paris.\n\n[[ ## answer ## ]]\nParis\n\n[[ ## completed ## ]]".to_string(),
        )
        .await
        .unwrap();
    let output = adapter.parse_response(&signature, response.output);

    assert_eq!(output.len(), 2);
    assert_eq!(
        output.get("reasoning").unwrap(),
        "The capital of France is Paris."
    );
    assert_eq!(output.get("answer").unwrap(), "Paris");
}

#[allow(dead_code)]
#[derive(JsonSchema)]
struct TestOutput {
    pub reasoning: String,
    pub rating: i8,
}

#[allow(dead_code)]
#[Signature]
struct TestSignature2 {
    #[input]
    pub problem: String,
    #[input]
    pub hint: i8,
    #[output]
    pub output: TestOutput,
}

#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_chat_adapter_with_multiple_fields_and_output_schema() {
    let signature = TestSignature2::new();

    let lm = DummyLM::default();
    let adapter = ChatAdapter;

    let messages: Chat = adapter.format(
        &signature,
        Example::new(
            hashmap! {
                "problem".to_string() => "What is the capital of France?".to_string().into(),
                "hint".to_string() => "The capital of France is Paris.".to_string().into(),
            },
            vec!["problem".to_string(), "hint".to_string()],
            vec!["output".to_string()],
        ),
    );

    let json_value = messages.to_json();
    let json = json_value.as_array().unwrap();

    assert_eq!(messages.len(), 2);
    assert_eq!(json[0]["role"], "system");
    assert_eq!(json[1]["role"], "user");

    assert_eq!(
        json[0]["content"],
        "Your input fields are:\n1. `problem` (String)\n2. `hint` (i8)\n\nYour output fields are:\n1. `output` (TestOutput)\n\nAll interactions will be structured in the following way, with the appropriate values filled in.\n\n[[ ## problem ## ]]\nproblem\n\n[[ ## hint ## ]]\nhint\t# note: the value you produce must be a single i8 value\n\n[[ ## output ## ]]\noutput\t# note: the value you produce must adhere to the JSON schema: {\"reasoning\":{\"type\":\"string\"},\"rating\":{\"type\":\"integer\",\"format\":\"int8\",\"minimum\":-128,\"maximum\":127}}\n\n[[ ## completed ## ]]\n\nIn adhering to this structure, your objective is:\n\tGiven the fields `problem`, `hint`, produce the fields `output`.".to_string()
    );
    assert_eq!(
        json[1]["content"],
        "[[ ## problem ## ]]\nWhat is the capital of France?\n\n[[ ## hint ## ]]\nThe capital of France is Paris.\n\nRespond with the corresponding output fields, starting with the field `output` (must be formatted as valid Rust TestOutput), and then ending with the marker for `completed`."
    );

    let test_example = example! {
        "problem": "input" => "What is the capital of France?",
        "hint": "output" => "The capital of France is Paris.",
        "output": "output" => "{\"reasoning\": \"The capital of France is Paris.\", \"rating\": 5}"
    };

    let response = lm
        .call(
            test_example,
            Chat::new(vec![
                Message::system("You are a helpful assistant."),
                Message::user("Hello, world!"),
            ]),
            "[[ ## output ## ]]\n{\"reasoning\": \"The capital of France is Paris.\", \"rating\": 5}\n\n[[ ## completed ## ]]".to_string(),
        )
        .await
        .unwrap();
    let output = adapter.parse_response(&signature, response.output);

    assert_eq!(output.len(), 1);

    let parsed_output: serde_json::Value =
        serde_json::from_str("{\"reasoning\": \"The capital of France is Paris.\", \"rating\": 5}")
            .unwrap();
    assert_eq!(
        output.get("output").unwrap()["reasoning"],
        parsed_output["reasoning"]
    );
    assert_eq!(
        output.get("output").unwrap()["rating"],
        parsed_output["rating"]
    );
}

#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_chat_adapter_with_demos() {
    let mut signature = sign! {
        (problem: String) -> answer: String
    };

    let adapter = ChatAdapter;

    // Create demo examples
    let demo1 = Example::new(
        hashmap! {
            "problem".to_string() => "What is 2 + 2?".to_string().into(),
            "answer".to_string() => "4".to_string().into(),
        },
        vec!["problem".to_string()],
        vec!["answer".to_string()],
    );

    let demo2 = Example::new(
        hashmap! {
            "problem".to_string() => "What is the largest planet?".to_string().into(),
            "answer".to_string() => "Jupiter".to_string().into(),
        },
        vec!["problem".to_string()],
        vec!["answer".to_string()],
    );

    signature.set_demos(vec![demo1, demo2]).unwrap();

    let current_input = Example::new(
        hashmap! {
            "problem".to_string() => "What is the capital of France?".to_string().into(),
        },
        vec!["problem".to_string()],
        vec!["answer".to_string()],
    );

    let messages: Chat = adapter.format(&signature, current_input);

    let json_value = messages.to_json();
    let json = json_value.as_array().unwrap();

    // Should have system message + 2 demo pairs (user + assistant) + current user message
    assert_eq!(messages.len(), 6);
    assert_eq!(json[0]["role"], "system");
    assert_eq!(json[1]["role"], "user");
    assert_eq!(json[2]["role"], "assistant");
    assert_eq!(json[3]["role"], "user");
    assert_eq!(json[4]["role"], "assistant");
    assert_eq!(json[5]["role"], "user");

    // Check demo 1 formatting
    assert!(
        json[1]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## problem ## ]]\nWhat is 2 + 2?")
    );
    assert!(
        json[2]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## answer ## ]]\n4")
    );
    assert!(
        json[2]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## completed ## ]]")
    );

    // Check demo 2 formatting
    assert!(
        json[3]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## problem ## ]]\nWhat is the largest planet?")
    );
    assert!(
        json[4]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## answer ## ]]\nJupiter")
    );
    assert!(
        json[4]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## completed ## ]]")
    );

    // Check current input formatting
    assert!(
        json[5]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## problem ## ]]\nWhat is the capital of France?")
    );
    assert!(
        json[5]["content"]
            .as_str()
            .unwrap()
            .contains("Respond with the corresponding output fields")
    );
}

#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_chat_adapter_with_empty_demos() {
    let mut signature = sign! {
        (problem: String) -> answer: String
    };

    let adapter = ChatAdapter;

    let current_input = Example::new(
        hashmap! {
            "problem".to_string() => "What is the capital of France?".to_string().into(),
        },
        vec!["problem".to_string()],
        vec!["answer".to_string()],
    );
    signature.set_demos(vec![]).unwrap();

    let messages: Chat = adapter.format(&signature, current_input);

    let json_value = messages.to_json();
    let json = json_value.as_array().unwrap();

    // Should only have system message + current user message (no demos)
    assert_eq!(messages.len(), 2);
    assert_eq!(json[0]["role"], "system");
    assert_eq!(json[1]["role"], "user");

    // Check current input formatting
    assert!(
        json[1]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## problem ## ]]\nWhat is the capital of France?")
    );
}

#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_chat_adapter_demo_format_multiple_fields() {
    let mut signature = TestSignature::new();

    let adapter = ChatAdapter;

    let demo = Example::new(
        hashmap! {
            "problem".to_string() => "What is 5 * 6?".to_string().into(),
            "hint".to_string() => "Think about multiplication".to_string().into(),
            "reasoning".to_string() => "5 multiplied by 6 equals 30".to_string().into(),
            "answer".to_string() => "30".to_string().into(),
        },
        vec!["problem".to_string(), "hint".to_string()],
        vec!["reasoning".to_string(), "answer".to_string()],
    );

    signature.set_demos(vec![demo]).unwrap();

    let current_input = Example::new(
        hashmap! {
            "problem".to_string() => "What is 3 + 7?".to_string().into(),
            "hint".to_string() => "Simple addition".to_string().into(),
        },
        vec!["problem".to_string(), "hint".to_string()],
        vec!["reasoning".to_string(), "answer".to_string()],
    );

    let messages: Chat = adapter.format(&signature, current_input);

    let json_value = messages.to_json();
    let json = json_value.as_array().unwrap();

    // Should have system + demo user + demo assistant + current user
    assert_eq!(messages.len(), 4);

    // Check demo user message contains both input fields
    assert!(
        json[1]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## problem ## ]]\nWhat is 5 * 6?")
    );
    assert!(
        json[1]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## hint ## ]]\nThink about multiplication")
    );

    // Check demo assistant message contains both output fields and completion marker
    assert!(
        json[2]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## reasoning ## ]]\n5 multiplied by 6 equals 30")
    );
    assert!(
        json[2]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## answer ## ]]\n30")
    );
    assert!(
        json[2]["content"]
            .as_str()
            .unwrap()
            .contains("[[ ## completed ## ]]")
    );
}

#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_chat_adapter_with_cache_hit() {
    let dummy_lm = DummyLM::default();

    // Create test input example
    let input = example! {
        "question": "input" => "What is 2 + 2?",
    };

    // Create chat messages
    let chat = Chat::new(vec![
        Message::system("You are a helpful assistant."),
        Message::user("What is 2 + 2?"),
    ]);

    // First call - will cache the result
    let response1 = dummy_lm
        .call(
            input.clone(),
            chat.clone(),
            "[[ ## answer ## ]]\n4\n\n[[ ## completed ## ]]".to_string(),
        )
        .await
        .unwrap();

    // Second call with same input - should use cached result internally
    let response2 = dummy_lm
        .call(
            input.clone(),
            chat.clone(),
            "[[ ## answer ## ]]\n4\n\n[[ ## completed ## ]]".to_string(),
        )
        .await
        .unwrap();

    // Both responses should be identical
    assert_eq!(response1.output.content(), response2.output.content());
    assert_eq!(
        response1.output.content(),
        "[[ ## answer ## ]]\n4\n\n[[ ## completed ## ]]"
    );
}

#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_chat_adapter_cache_miss_different_inputs() {
    // Create DummyLM with cache enabled

    let cache_handler = Arc::new(Mutex::new(Cache::new().await));
    let dummy_lm = DummyLM::builder()
        .cache_handler(cache_handler)
        .api_key("test_key".to_string())
        .build();

    // First input
    let input1 = example! {
        "question": "input" => "What is 2 + 2?",
    };

    // Second (different) input
    let input2 = example! {
        "question": "input" => "What is 3 + 3?",
    };

    let chat = Chat::new(vec![
        Message::system("You are a helpful assistant."),
        Message::user("Calculate the sum."),
    ]);

    // Call with first input
    let response1 = dummy_lm
        .call(
            input1.clone(),
            chat.clone(),
            "[[ ## answer ## ]]\n4\n\n[[ ## completed ## ]]".to_string(),
        )
        .await
        .unwrap();

    // Call with second input (different input, should not hit cache)
    let response2 = dummy_lm
        .call(
            input2.clone(),
            chat.clone(),
            "[[ ## answer ## ]]\n6\n\n[[ ## completed ## ]]".to_string(),
        )
        .await
        .unwrap();

    // Different inputs should produce different responses
    assert_eq!(
        response1.output.content(),
        "[[ ## answer ## ]]\n4\n\n[[ ## completed ## ]]"
    );
    assert_eq!(
        response2.output.content(),
        "[[ ## answer ## ]]\n6\n\n[[ ## completed ## ]]"
    );
    assert_ne!(response1.output.content(), response2.output.content());
}

#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_chat_adapter_cache_disabled() {
    // Create DummyLM with cache disabled
    let dummy_lm = DummyLM::default();

    // Create test input
    let input = example! {
        "question": "input" => "What is 2 + 2?",
    };

    let chat = Chat::new(vec![
        Message::system("You are a helpful assistant."),
        Message::user("What is 2 + 2?"),
    ]);

    // Call without cache - should work normally
    let response = dummy_lm
        .call(
            input.clone(),
            chat.clone(),
            "[[ ## answer ## ]]\n4\n\n[[ ## completed ## ]]".to_string(),
        )
        .await
        .unwrap();

    assert_eq!(
        response.output.content(),
        "[[ ## answer ## ]]\n4\n\n[[ ## completed ## ]]"
    );

    // Verify cache handler is None when cache is disabled
    assert!(dummy_lm.cache_handler.is_none());
}