llm-toolkit 0.63.1

A low-level, unopinionated Rust toolkit for the LLM last mile problem.
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
//! A trait and macros for powerful, type-safe prompt generation.

use minijinja::Environment;
use serde::Serialize;

/// Represents a part of a multimodal prompt.
///
/// This enum allows prompts to contain different types of content,
/// such as text and images, enabling multimodal LLM interactions.
#[derive(Debug, Clone)]
pub enum PromptPart {
    /// Text content in the prompt.
    Text(String),
    /// Image content with media type and binary data.
    Image {
        /// The MIME media type (e.g., "image/jpeg", "image/png").
        media_type: String,
        /// The raw image data.
        data: Vec<u8>,
    },
    // Future variants like Audio or Video can be added here
}

/// A trait for converting any type into a string suitable for an LLM prompt.
///
/// This trait provides a standard interface for converting various types
/// into strings that can be used as prompts for language models.
///
/// # Example
///
/// ```
/// use llm_toolkit::prompt::ToPrompt;
///
/// // Common types have ToPrompt implementations
/// let number = 42;
/// assert_eq!(number.to_prompt(), "42");
///
/// let text = "Hello, LLM!";
/// assert_eq!(text.to_prompt(), "Hello, LLM!");
/// ```
///
/// # Custom Implementation
///
/// You can also implement `ToPrompt` directly for your own types:
///
/// ```
/// use llm_toolkit::prompt::{ToPrompt, PromptPart};
/// use std::fmt;
///
/// struct CustomType {
///     value: String,
/// }
///
/// impl fmt::Display for CustomType {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "{}", self.value)
///     }
/// }
///
/// // By implementing ToPrompt directly, you can control the conversion.
/// impl ToPrompt for CustomType {
///     fn to_prompt_parts(&self) -> Vec<PromptPart> {
///         vec![PromptPart::Text(self.to_string())]
///     }
///
///     fn to_prompt(&self) -> String {
///         self.to_string()
///     }
/// }
///
/// let custom = CustomType { value: "custom".to_string() };
/// assert_eq!(custom.to_prompt(), "custom");
/// ```
pub trait ToPrompt {
    /// Converts the object into a vector of `PromptPart`s based on a mode.
    ///
    /// This is the core method that `derive(ToPrompt)` will implement.
    /// The `mode` argument allows for different prompt representations, such as:
    /// - "full": A comprehensive prompt with schema and examples.
    /// - "schema_only": Just the data structure's schema.
    /// - "example_only": Just a concrete example.
    ///
    /// The default implementation ignores the mode and calls `to_prompt_parts`
    /// for backward compatibility with manual implementations.
    fn to_prompt_parts_with_mode(&self, mode: &str) -> Vec<PromptPart> {
        // Default implementation for backward compatibility
        let _ = mode; // Unused in default impl
        self.to_prompt_parts()
    }

    /// Converts the object into a prompt string based on a mode.
    ///
    /// This method extracts only the text portions from `to_prompt_parts_with_mode()`.
    fn to_prompt_with_mode(&self, mode: &str) -> String {
        self.to_prompt_parts_with_mode(mode)
            .iter()
            .filter_map(|part| match part {
                PromptPart::Text(text) => Some(text.as_str()),
                _ => None,
            })
            .collect::<Vec<_>>()
            .join("")
    }

    /// Converts the object into a vector of `PromptPart`s using the default "full" mode.
    ///
    /// This method enables multimodal prompt generation by returning
    /// a collection of prompt parts that can include text, images, and
    /// other media types.
    fn to_prompt_parts(&self) -> Vec<PromptPart> {
        self.to_prompt_parts_with_mode("full")
    }

    /// Converts the object into a prompt string using the default "full" mode.
    ///
    /// This method provides backward compatibility by extracting only
    /// the text portions from `to_prompt_parts()` and joining them.
    fn to_prompt(&self) -> String {
        self.to_prompt_with_mode("full")
    }

    /// Returns a schema-level prompt for the type itself.
    ///
    /// For enums, this returns all possible variants with their descriptions.
    /// For structs, this returns the field schema.
    ///
    /// Unlike instance methods like `to_prompt()`, this is a type-level method
    /// that doesn't require an instance.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Enum: get all variants
    /// let schema = MyEnum::prompt_schema();
    ///
    /// // Struct: get field schema
    /// let schema = MyStruct::prompt_schema();
    /// ```
    fn prompt_schema() -> String {
        String::new() // Default implementation returns empty string
    }
}

// Add implementations for common types

impl ToPrompt for String {
    fn to_prompt_parts(&self) -> Vec<PromptPart> {
        vec![PromptPart::Text(self.clone())]
    }

    fn to_prompt(&self) -> String {
        self.clone()
    }
}

impl ToPrompt for &str {
    fn to_prompt_parts(&self) -> Vec<PromptPart> {
        vec![PromptPart::Text(self.to_string())]
    }

    fn to_prompt(&self) -> String {
        self.to_string()
    }
}

impl ToPrompt for bool {
    fn to_prompt_parts(&self) -> Vec<PromptPart> {
        vec![PromptPart::Text(self.to_string())]
    }

    fn to_prompt(&self) -> String {
        self.to_string()
    }
}

impl ToPrompt for char {
    fn to_prompt_parts(&self) -> Vec<PromptPart> {
        vec![PromptPart::Text(self.to_string())]
    }

    fn to_prompt(&self) -> String {
        self.to_string()
    }
}

macro_rules! impl_to_prompt_for_numbers {
    ($($t:ty),*) => {
        $(
            impl ToPrompt for $t {
                fn to_prompt_parts(&self) -> Vec<PromptPart> {
                    vec![PromptPart::Text(self.to_string())]
                }

                fn to_prompt(&self) -> String {
                    self.to_string()
                }
            }
        )*
    };
}

impl_to_prompt_for_numbers!(
    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
);

// Implement ToPrompt for Vec<T> where T: ToPrompt
impl<T: ToPrompt> ToPrompt for Vec<T> {
    fn to_prompt_parts(&self) -> Vec<PromptPart> {
        vec![PromptPart::Text(self.to_prompt())]
    }

    fn to_prompt(&self) -> String {
        format!(
            "[{}]",
            self.iter()
                .map(|item| item.to_prompt())
                .collect::<Vec<_>>()
                .join(", ")
        )
    }
}

// Implement ToPrompt for Option<T> where T: ToPrompt
impl<T: ToPrompt> ToPrompt for Option<T> {
    fn to_prompt_parts(&self) -> Vec<PromptPart> {
        vec![PromptPart::Text(self.to_prompt())]
    }

    fn to_prompt(&self) -> String {
        match self {
            Some(value) => value.to_prompt(),
            None => String::new(),
        }
    }
}

/// Renders a prompt from a template string and a serializable context.
///
/// This is the underlying function for the `prompt!` macro.
pub fn render_prompt<T: Serialize>(template: &str, context: T) -> Result<String, minijinja::Error> {
    let mut env = Environment::new();
    env.add_template("prompt", template)?;
    let tmpl = env.get_template("prompt")?;
    tmpl.render(context)
}

/// Creates a prompt string from a template and key-value pairs.
///
/// This macro provides a `println!`-like experience for building prompts
/// from various data sources. It leverages `minijinja` for templating.
///
/// # Example
///
/// ```
/// use llm_toolkit::prompt;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct User {
///     name: &'static str,
///     role: &'static str,
/// }
///
/// let user = User { name: "Mai", role: "UX Engineer" };
/// let task = "designing a new macro";
///
/// let p = prompt!(
///     "User {{user.name}} ({{user.role}}) is currently {{task}}.",
///     user = user,
///     task = task
/// ).unwrap();
///
/// assert_eq!(p, "User Mai (UX Engineer) is currently designing a new macro.");
/// ```
#[macro_export]
macro_rules! prompt {
    ($template:expr, $($key:ident = $value:expr),* $(,)?) => {
        $crate::prompt::render_prompt($template, minijinja::context!($($key => $value),*))
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Serialize;
    use std::fmt::Display;

    enum TestEnum {
        VariantA,
        VariantB,
    }

    impl Display for TestEnum {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                TestEnum::VariantA => write!(f, "Variant A"),
                TestEnum::VariantB => write!(f, "Variant B"),
            }
        }
    }

    impl ToPrompt for TestEnum {
        fn to_prompt_parts(&self) -> Vec<PromptPart> {
            vec![PromptPart::Text(self.to_string())]
        }

        fn to_prompt(&self) -> String {
            self.to_string()
        }
    }

    #[test]
    fn test_to_prompt_for_enum() {
        let variant = TestEnum::VariantA;
        assert_eq!(variant.to_prompt(), "Variant A");
    }

    #[test]
    fn test_to_prompt_for_enum_variant_b() {
        let variant = TestEnum::VariantB;
        assert_eq!(variant.to_prompt(), "Variant B");
    }

    #[test]
    fn test_to_prompt_for_string() {
        let s = "hello world";
        assert_eq!(s.to_prompt(), "hello world");
    }

    #[test]
    fn test_to_prompt_for_number() {
        let n = 42;
        assert_eq!(n.to_prompt(), "42");
    }

    #[test]
    fn test_to_prompt_for_option_some() {
        let opt: Option<String> = Some("hello".to_string());
        assert_eq!(opt.to_prompt(), "hello");
    }

    #[test]
    fn test_to_prompt_for_option_none() {
        let opt: Option<String> = None;
        assert_eq!(opt.to_prompt(), "");
    }

    #[test]
    fn test_to_prompt_for_option_number() {
        let opt_some: Option<i32> = Some(42);
        assert_eq!(opt_some.to_prompt(), "42");

        let opt_none: Option<i32> = None;
        assert_eq!(opt_none.to_prompt(), "");
    }

    #[test]
    fn test_to_prompt_parts_for_option() {
        let opt: Option<String> = Some("test".to_string());
        let parts = opt.to_prompt_parts();
        assert_eq!(parts.len(), 1);
        match &parts[0] {
            PromptPart::Text(text) => assert_eq!(text, "test"),
            _ => panic!("Expected PromptPart::Text"),
        }
    }

    #[derive(Serialize)]
    struct SystemInfo {
        version: &'static str,
        os: &'static str,
    }

    #[test]
    fn test_prompt_macro_simple() {
        let user = "Yui";
        let task = "implementation";
        let prompt = prompt!(
            "User {{user}} is working on the {{task}}.",
            user = user,
            task = task
        )
        .unwrap();
        assert_eq!(prompt, "User Yui is working on the implementation.");
    }

    #[test]
    fn test_prompt_macro_with_struct() {
        let sys = SystemInfo {
            version: "0.1.0",
            os: "Rust",
        };
        let prompt = prompt!("System: {{sys.version}} on {{sys.os}}", sys = sys).unwrap();
        assert_eq!(prompt, "System: 0.1.0 on Rust");
    }

    #[test]
    fn test_prompt_macro_mixed() {
        let user = "Mai";
        let sys = SystemInfo {
            version: "0.1.0",
            os: "Rust",
        };
        let prompt = prompt!(
            "User {{user}} is using {{sys.os}} v{{sys.version}}.",
            user = user,
            sys = sys
        )
        .unwrap();
        assert_eq!(prompt, "User Mai is using Rust v0.1.0.");
    }

    #[test]
    fn test_to_prompt_for_vec_of_strings() {
        let items = vec!["apple", "banana", "cherry"];
        assert_eq!(items.to_prompt(), "[apple, banana, cherry]");
    }

    #[test]
    fn test_to_prompt_for_vec_of_numbers() {
        let numbers = vec![1, 2, 3, 42];
        assert_eq!(numbers.to_prompt(), "[1, 2, 3, 42]");
    }

    #[test]
    fn test_to_prompt_for_empty_vec() {
        let empty: Vec<String> = vec![];
        assert_eq!(empty.to_prompt(), "[]");
    }

    #[test]
    fn test_to_prompt_for_nested_vec() {
        let nested = vec![vec![1, 2], vec![3, 4]];
        assert_eq!(nested.to_prompt(), "[[1, 2], [3, 4]]");
    }

    #[test]
    fn test_to_prompt_parts_for_vec() {
        let items = vec!["a", "b", "c"];
        let parts = items.to_prompt_parts();
        assert_eq!(parts.len(), 1);
        match &parts[0] {
            PromptPart::Text(text) => assert_eq!(text, "[a, b, c]"),
            _ => panic!("Expected Text variant"),
        }
    }

    #[test]
    fn test_to_prompt_for_option_vec() {
        // Option<Vec<T>>
        let opt_vec_some: Option<Vec<String>> = Some(vec!["a".to_string(), "b".to_string()]);
        assert_eq!(opt_vec_some.to_prompt(), "[a, b]");

        let opt_vec_none: Option<Vec<String>> = None;
        assert_eq!(opt_vec_none.to_prompt(), "");
    }

    #[test]
    fn test_to_prompt_for_vec_option() {
        // Vec<Option<T>>
        let vec_opts = vec![Some("hello".to_string()), None, Some("world".to_string())];
        // Each Option is converted: Some("hello") -> "hello", None -> ""
        assert_eq!(vec_opts.to_prompt(), "[hello, , world]");
    }

    #[test]
    fn test_to_prompt_for_option_none_with_parts() {
        let opt: Option<String> = None;
        let parts = opt.to_prompt_parts();
        assert_eq!(parts.len(), 1);
        match &parts[0] {
            PromptPart::Text(text) => assert_eq!(text, ""),
            _ => panic!("Expected PromptPart::Text"),
        }
    }

    #[test]
    fn test_prompt_macro_no_args() {
        let prompt = prompt!("This is a static prompt.",).unwrap();
        assert_eq!(prompt, "This is a static prompt.");
    }

    #[test]
    fn test_render_prompt_with_json_value_dot_notation() {
        use serde_json::json;

        let context = json!({
            "user": {
                "name": "Alice",
                "age": 30,
                "profile": {
                    "role": "Developer"
                }
            }
        });

        let template =
            "{{ user.name }} is {{ user.age }} years old and works as {{ user.profile.role }}";
        let result = render_prompt(template, &context).unwrap();

        assert_eq!(result, "Alice is 30 years old and works as Developer");
    }

    #[test]
    fn test_render_prompt_with_hashmap_json_value() {
        use serde_json::json;
        use std::collections::HashMap;

        let mut context = HashMap::new();
        context.insert(
            "step_1_output".to_string(),
            json!({
                "result": "success",
                "data": {
                    "count": 42
                }
            }),
        );
        context.insert("task".to_string(), json!("analysis"));

        let template = "Task: {{ task }}, Result: {{ step_1_output.result }}, Count: {{ step_1_output.data.count }}";
        let result = render_prompt(template, &context).unwrap();

        assert_eq!(result, "Task: analysis, Result: success, Count: 42");
    }

    #[test]
    fn test_render_prompt_with_array_in_json_template() {
        use serde_json::json;
        use std::collections::HashMap;

        let mut context = HashMap::new();
        context.insert(
            "user_request".to_string(),
            json!({
                "narrative_keywords": ["betrayal", "redemption", "sacrifice"]
            }),
        );

        // Test: Embedding array directly in JSON template (common pattern in strategy generation)
        let template = r#"{"keywords": {{ user_request.narrative_keywords }}}"#;
        let result = render_prompt(template, &context).unwrap();

        // Verify the result is valid JSON
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["keywords"][0], "betrayal");
        assert_eq!(parsed["keywords"][1], "redemption");
        assert_eq!(parsed["keywords"][2], "sacrifice");
    }

    #[test]
    fn test_render_prompt_with_object_in_json_template() {
        use serde_json::json;
        use std::collections::HashMap;

        let mut context = HashMap::new();
        context.insert(
            "user_request".to_string(),
            json!({
                "config": {
                    "theme": "dark_fantasy",
                    "complexity": 5
                }
            }),
        );

        // Test: Embedding object directly in JSON template
        let template = r#"{"settings": {{ user_request.config }}}"#;
        let result = render_prompt(template, &context).unwrap();

        // Verify the result is valid JSON
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["settings"]["theme"], "dark_fantasy");
        assert_eq!(parsed["settings"]["complexity"], 5);
    }

    #[test]
    fn test_render_prompt_mixed_json_template() {
        use serde_json::json;
        use std::collections::HashMap;

        let mut context = HashMap::new();
        context.insert(
            "world_concept".to_string(),
            json!({
                "concept": "A world where identity is volatile"
            }),
        );
        context.insert(
            "user_request".to_string(),
            json!({
                "narrative_keywords": ["betrayal", "redemption"],
                "theme": "dark fantasy"
            }),
        );

        // Test: Complex case with both array and quoted string (like the actual error case)
        let template = r#"{"concept": "{{ world_concept.concept }}", "keywords": {{ user_request.narrative_keywords }}, "theme": "{{ user_request.theme }}"}"#;
        let result = render_prompt(template, &context).unwrap();

        // Verify the result is valid JSON
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["concept"], "A world where identity is volatile");
        assert_eq!(parsed["keywords"][0], "betrayal");
        assert_eq!(parsed["theme"], "dark fantasy");
    }
}

#[derive(Debug, thiserror::Error)]
pub enum PromptSetError {
    #[error("Target '{target}' not found. Available targets: {available:?}")]
    TargetNotFound {
        target: String,
        available: Vec<String>,
    },
    #[error("Failed to render prompt for target '{target}': {source}")]
    RenderFailed {
        target: String,
        source: minijinja::Error,
    },
}

/// A trait for types that can generate multiple named prompt targets.
///
/// This trait enables a single data structure to produce different prompt formats
/// for various use cases (e.g., human-readable vs. machine-parsable formats).
///
/// # Example
///
/// ```ignore
/// use llm_toolkit::prompt::{ToPromptSet, PromptPart};
/// use serde::Serialize;
///
/// #[derive(ToPromptSet, Serialize)]
/// #[prompt_for(name = "Visual", template = "## {{title}}\n\n> {{description}}")]
/// struct Task {
///     title: String,
///     description: String,
///
///     #[prompt_for(name = "Agent")]
///     priority: u8,
///
///     #[prompt_for(name = "Agent", rename = "internal_id")]
///     id: u64,
///
///     #[prompt_for(skip)]
///     is_dirty: bool,
/// }
///
/// let task = Task {
///     title: "Implement feature".to_string(),
///     description: "Add new functionality".to_string(),
///     priority: 1,
///     id: 42,
///     is_dirty: false,
/// };
///
/// // Generate visual prompt
/// let visual_prompt = task.to_prompt_for("Visual")?;
///
/// // Generate agent prompt
/// let agent_prompt = task.to_prompt_for("Agent")?;
/// ```
pub trait ToPromptSet {
    /// Generates multimodal prompt parts for the specified target.
    fn to_prompt_parts_for(&self, target: &str) -> Result<Vec<PromptPart>, PromptSetError>;

    /// Generates a text prompt for the specified target.
    ///
    /// This method extracts only the text portions from `to_prompt_parts_for()`
    /// and joins them together.
    fn to_prompt_for(&self, target: &str) -> Result<String, PromptSetError> {
        let parts = self.to_prompt_parts_for(target)?;
        let text = parts
            .iter()
            .filter_map(|part| match part {
                PromptPart::Text(text) => Some(text.as_str()),
                _ => None,
            })
            .collect::<Vec<_>>()
            .join("\n");
        Ok(text)
    }
}

/// A trait for generating a prompt for a specific target type.
///
/// This allows a type (e.g., a `Tool`) to define how it should be represented
/// in a prompt when provided with a target context (e.g., an `Agent`).
pub trait ToPromptFor<T> {
    /// Generates a prompt for the given target, using a specific mode.
    fn to_prompt_for_with_mode(&self, target: &T, mode: &str) -> String;

    /// Generates a prompt for the given target using the default "full" mode.
    ///
    /// This method provides backward compatibility by calling the `_with_mode`
    /// variant with a default mode.
    fn to_prompt_for(&self, target: &T) -> String {
        self.to_prompt_for_with_mode(target, "full")
    }
}