llm_toolkit/prompt.rs
1//! A trait and macros for powerful, type-safe prompt generation.
2
3use minijinja::Environment;
4use serde::Serialize;
5
6/// Represents a part of a multimodal prompt.
7///
8/// This enum allows prompts to contain different types of content,
9/// such as text and images, enabling multimodal LLM interactions.
10#[derive(Debug, Clone)]
11pub enum PromptPart {
12 /// Text content in the prompt.
13 Text(String),
14 /// Image content with media type and binary data.
15 Image {
16 /// The MIME media type (e.g., "image/jpeg", "image/png").
17 media_type: String,
18 /// The raw image data.
19 data: Vec<u8>,
20 },
21 // Future variants like Audio or Video can be added here
22}
23
24/// A trait for converting any type into a string suitable for an LLM prompt.
25///
26/// This trait provides a standard interface for converting various types
27/// into strings that can be used as prompts for language models.
28///
29/// # Example
30///
31/// ```
32/// use llm_toolkit::prompt::ToPrompt;
33///
34/// // Common types have ToPrompt implementations
35/// let number = 42;
36/// assert_eq!(number.to_prompt(), "42");
37///
38/// let text = "Hello, LLM!";
39/// assert_eq!(text.to_prompt(), "Hello, LLM!");
40/// ```
41///
42/// # Custom Implementation
43///
44/// You can also implement `ToPrompt` directly for your own types:
45///
46/// ```
47/// use llm_toolkit::prompt::{ToPrompt, PromptPart};
48/// use std::fmt;
49///
50/// struct CustomType {
51/// value: String,
52/// }
53///
54/// impl fmt::Display for CustomType {
55/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56/// write!(f, "{}", self.value)
57/// }
58/// }
59///
60/// // By implementing ToPrompt directly, you can control the conversion.
61/// impl ToPrompt for CustomType {
62/// fn to_prompt_parts(&self) -> Vec<PromptPart> {
63/// vec![PromptPart::Text(self.to_string())]
64/// }
65///
66/// fn to_prompt(&self) -> String {
67/// self.to_string()
68/// }
69/// }
70///
71/// let custom = CustomType { value: "custom".to_string() };
72/// assert_eq!(custom.to_prompt(), "custom");
73/// ```
74pub trait ToPrompt {
75 /// Converts the object into a vector of `PromptPart`s based on a mode.
76 ///
77 /// This is the core method that `derive(ToPrompt)` will implement.
78 /// The `mode` argument allows for different prompt representations, such as:
79 /// - "full": A comprehensive prompt with schema and examples.
80 /// - "schema_only": Just the data structure's schema.
81 /// - "example_only": Just a concrete example.
82 ///
83 /// The default implementation ignores the mode and calls `to_prompt_parts`
84 /// for backward compatibility with manual implementations.
85 fn to_prompt_parts_with_mode(&self, mode: &str) -> Vec<PromptPart> {
86 // Default implementation for backward compatibility
87 let _ = mode; // Unused in default impl
88 self.to_prompt_parts()
89 }
90
91 /// Converts the object into a prompt string based on a mode.
92 ///
93 /// This method extracts only the text portions from `to_prompt_parts_with_mode()`.
94 fn to_prompt_with_mode(&self, mode: &str) -> String {
95 self.to_prompt_parts_with_mode(mode)
96 .iter()
97 .filter_map(|part| match part {
98 PromptPart::Text(text) => Some(text.as_str()),
99 _ => None,
100 })
101 .collect::<Vec<_>>()
102 .join("")
103 }
104
105 /// Converts the object into a vector of `PromptPart`s using the default "full" mode.
106 ///
107 /// This method enables multimodal prompt generation by returning
108 /// a collection of prompt parts that can include text, images, and
109 /// other media types.
110 fn to_prompt_parts(&self) -> Vec<PromptPart> {
111 self.to_prompt_parts_with_mode("full")
112 }
113
114 /// Converts the object into a prompt string using the default "full" mode.
115 ///
116 /// This method provides backward compatibility by extracting only
117 /// the text portions from `to_prompt_parts()` and joining them.
118 fn to_prompt(&self) -> String {
119 self.to_prompt_with_mode("full")
120 }
121
122 /// Returns a schema-level prompt for the type itself.
123 ///
124 /// For enums, this returns all possible variants with their descriptions.
125 /// For structs, this returns the field schema.
126 ///
127 /// Unlike instance methods like `to_prompt()`, this is a type-level method
128 /// that doesn't require an instance.
129 ///
130 /// # Examples
131 ///
132 /// ```ignore
133 /// // Enum: get all variants
134 /// let schema = MyEnum::prompt_schema();
135 ///
136 /// // Struct: get field schema
137 /// let schema = MyStruct::prompt_schema();
138 /// ```
139 fn prompt_schema() -> String {
140 String::new() // Default implementation returns empty string
141 }
142}
143
144// Add implementations for common types
145
146impl ToPrompt for String {
147 fn to_prompt_parts(&self) -> Vec<PromptPart> {
148 vec![PromptPart::Text(self.clone())]
149 }
150
151 fn to_prompt(&self) -> String {
152 self.clone()
153 }
154}
155
156impl ToPrompt for &str {
157 fn to_prompt_parts(&self) -> Vec<PromptPart> {
158 vec![PromptPart::Text(self.to_string())]
159 }
160
161 fn to_prompt(&self) -> String {
162 self.to_string()
163 }
164}
165
166impl ToPrompt for bool {
167 fn to_prompt_parts(&self) -> Vec<PromptPart> {
168 vec![PromptPart::Text(self.to_string())]
169 }
170
171 fn to_prompt(&self) -> String {
172 self.to_string()
173 }
174}
175
176impl ToPrompt for char {
177 fn to_prompt_parts(&self) -> Vec<PromptPart> {
178 vec![PromptPart::Text(self.to_string())]
179 }
180
181 fn to_prompt(&self) -> String {
182 self.to_string()
183 }
184}
185
186macro_rules! impl_to_prompt_for_numbers {
187 ($($t:ty),*) => {
188 $(
189 impl ToPrompt for $t {
190 fn to_prompt_parts(&self) -> Vec<PromptPart> {
191 vec![PromptPart::Text(self.to_string())]
192 }
193
194 fn to_prompt(&self) -> String {
195 self.to_string()
196 }
197 }
198 )*
199 };
200}
201
202impl_to_prompt_for_numbers!(
203 i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
204);
205
206/// Renders a prompt from a template string and a serializable context.
207///
208/// This is the underlying function for the `prompt!` macro.
209pub fn render_prompt<T: Serialize>(template: &str, context: T) -> Result<String, minijinja::Error> {
210 let mut env = Environment::new();
211 env.add_template("prompt", template)?;
212 let tmpl = env.get_template("prompt")?;
213 tmpl.render(context)
214}
215
216/// Creates a prompt string from a template and key-value pairs.
217///
218/// This macro provides a `println!`-like experience for building prompts
219/// from various data sources. It leverages `minijinja` for templating.
220///
221/// # Example
222///
223/// ```
224/// use llm_toolkit::prompt;
225/// use serde::Serialize;
226///
227/// #[derive(Serialize)]
228/// struct User {
229/// name: &'static str,
230/// role: &'static str,
231/// }
232///
233/// let user = User { name: "Mai", role: "UX Engineer" };
234/// let task = "designing a new macro";
235///
236/// let p = prompt!(
237/// "User {{user.name}} ({{user.role}}) is currently {{task}}.",
238/// user = user,
239/// task = task
240/// ).unwrap();
241///
242/// assert_eq!(p, "User Mai (UX Engineer) is currently designing a new macro.");
243/// ```
244#[macro_export]
245macro_rules! prompt {
246 ($template:expr, $($key:ident = $value:expr),* $(,)?) => {
247 $crate::prompt::render_prompt($template, minijinja::context!($($key => $value),*))
248 };
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254 use serde::Serialize;
255 use std::fmt::Display;
256
257 enum TestEnum {
258 VariantA,
259 VariantB,
260 }
261
262 impl Display for TestEnum {
263 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264 match self {
265 TestEnum::VariantA => write!(f, "Variant A"),
266 TestEnum::VariantB => write!(f, "Variant B"),
267 }
268 }
269 }
270
271 impl ToPrompt for TestEnum {
272 fn to_prompt_parts(&self) -> Vec<PromptPart> {
273 vec![PromptPart::Text(self.to_string())]
274 }
275
276 fn to_prompt(&self) -> String {
277 self.to_string()
278 }
279 }
280
281 #[test]
282 fn test_to_prompt_for_enum() {
283 let variant = TestEnum::VariantA;
284 assert_eq!(variant.to_prompt(), "Variant A");
285 }
286
287 #[test]
288 fn test_to_prompt_for_enum_variant_b() {
289 let variant = TestEnum::VariantB;
290 assert_eq!(variant.to_prompt(), "Variant B");
291 }
292
293 #[test]
294 fn test_to_prompt_for_string() {
295 let s = "hello world";
296 assert_eq!(s.to_prompt(), "hello world");
297 }
298
299 #[test]
300 fn test_to_prompt_for_number() {
301 let n = 42;
302 assert_eq!(n.to_prompt(), "42");
303 }
304
305 #[derive(Serialize)]
306 struct SystemInfo {
307 version: &'static str,
308 os: &'static str,
309 }
310
311 #[test]
312 fn test_prompt_macro_simple() {
313 let user = "Yui";
314 let task = "implementation";
315 let prompt = prompt!(
316 "User {{user}} is working on the {{task}}.",
317 user = user,
318 task = task
319 )
320 .unwrap();
321 assert_eq!(prompt, "User Yui is working on the implementation.");
322 }
323
324 #[test]
325 fn test_prompt_macro_with_struct() {
326 let sys = SystemInfo {
327 version: "0.1.0",
328 os: "Rust",
329 };
330 let prompt = prompt!("System: {{sys.version}} on {{sys.os}}", sys = sys).unwrap();
331 assert_eq!(prompt, "System: 0.1.0 on Rust");
332 }
333
334 #[test]
335 fn test_prompt_macro_mixed() {
336 let user = "Mai";
337 let sys = SystemInfo {
338 version: "0.1.0",
339 os: "Rust",
340 };
341 let prompt = prompt!(
342 "User {{user}} is using {{sys.os}} v{{sys.version}}.",
343 user = user,
344 sys = sys
345 )
346 .unwrap();
347 assert_eq!(prompt, "User Mai is using Rust v0.1.0.");
348 }
349
350 #[test]
351 fn test_prompt_macro_no_args() {
352 let prompt = prompt!("This is a static prompt.",).unwrap();
353 assert_eq!(prompt, "This is a static prompt.");
354 }
355}
356
357#[derive(Debug, thiserror::Error)]
358pub enum PromptSetError {
359 #[error("Target '{target}' not found. Available targets: {available:?}")]
360 TargetNotFound {
361 target: String,
362 available: Vec<String>,
363 },
364 #[error("Failed to render prompt for target '{target}': {source}")]
365 RenderFailed {
366 target: String,
367 source: minijinja::Error,
368 },
369}
370
371/// A trait for types that can generate multiple named prompt targets.
372///
373/// This trait enables a single data structure to produce different prompt formats
374/// for various use cases (e.g., human-readable vs. machine-parsable formats).
375///
376/// # Example
377///
378/// ```ignore
379/// use llm_toolkit::prompt::{ToPromptSet, PromptPart};
380/// use serde::Serialize;
381///
382/// #[derive(ToPromptSet, Serialize)]
383/// #[prompt_for(name = "Visual", template = "## {{title}}\n\n> {{description}}")]
384/// struct Task {
385/// title: String,
386/// description: String,
387///
388/// #[prompt_for(name = "Agent")]
389/// priority: u8,
390///
391/// #[prompt_for(name = "Agent", rename = "internal_id")]
392/// id: u64,
393///
394/// #[prompt_for(skip)]
395/// is_dirty: bool,
396/// }
397///
398/// let task = Task {
399/// title: "Implement feature".to_string(),
400/// description: "Add new functionality".to_string(),
401/// priority: 1,
402/// id: 42,
403/// is_dirty: false,
404/// };
405///
406/// // Generate visual prompt
407/// let visual_prompt = task.to_prompt_for("Visual")?;
408///
409/// // Generate agent prompt
410/// let agent_prompt = task.to_prompt_for("Agent")?;
411/// ```
412pub trait ToPromptSet {
413 /// Generates multimodal prompt parts for the specified target.
414 fn to_prompt_parts_for(&self, target: &str) -> Result<Vec<PromptPart>, PromptSetError>;
415
416 /// Generates a text prompt for the specified target.
417 ///
418 /// This method extracts only the text portions from `to_prompt_parts_for()`
419 /// and joins them together.
420 fn to_prompt_for(&self, target: &str) -> Result<String, PromptSetError> {
421 let parts = self.to_prompt_parts_for(target)?;
422 let text = parts
423 .iter()
424 .filter_map(|part| match part {
425 PromptPart::Text(text) => Some(text.as_str()),
426 _ => None,
427 })
428 .collect::<Vec<_>>()
429 .join("\n");
430 Ok(text)
431 }
432}
433
434/// A trait for generating a prompt for a specific target type.
435///
436/// This allows a type (e.g., a `Tool`) to define how it should be represented
437/// in a prompt when provided with a target context (e.g., an `Agent`).
438pub trait ToPromptFor<T> {
439 /// Generates a prompt for the given target, using a specific mode.
440 fn to_prompt_for_with_mode(&self, target: &T, mode: &str) -> String;
441
442 /// Generates a prompt for the given target using the default "full" mode.
443 ///
444 /// This method provides backward compatibility by calling the `_with_mode`
445 /// variant with a default mode.
446 fn to_prompt_for(&self, target: &T) -> String {
447 self.to_prompt_for_with_mode(target, "full")
448 }
449}