llm_toolkit/
lib.rs

1//! 'llm-toolkit' - A low-level Rust toolkit for the LLM last mile problem.
2//!
3//! This library provides a set of sharp, reliable, and unopinionated "tools"
4//! for building robust LLM-powered applications in Rust. It focuses on solving
5//! the common and frustrating problems that occur at the boundary between a
6//! strongly-typed Rust application and the unstructured, often unpredictable
7//! string-based responses from LLM APIs.
8
9/// A derive macro to implement the `ToPrompt` trait for structs.
10///
11/// This macro is available only when the `derive` feature is enabled.
12/// See the [crate-level documentation](index.html#2-structured-prompts-with-derivetoprompt) for usage examples.
13#[cfg(feature = "derive")]
14pub use llm_toolkit_macros::ToPrompt;
15
16/// A derive macro to implement the `ToPromptSet` trait for structs.
17///
18/// This macro is available only when the `derive` feature is enabled.
19#[cfg(feature = "derive")]
20pub use llm_toolkit_macros::ToPromptSet;
21
22/// A derive macro to implement the `ToPromptFor` trait for structs.
23///
24/// This macro is available only when the `derive` feature is enabled.
25#[cfg(feature = "derive")]
26pub use llm_toolkit_macros::ToPromptFor;
27
28/// A macro for creating examples sections in prompts.
29///
30/// This macro is available only when the `derive` feature is enabled.
31#[cfg(feature = "derive")]
32pub use llm_toolkit_macros::examples_section;
33
34pub mod extract;
35pub mod intent;
36pub mod multimodal;
37pub mod prompt;
38
39pub use extract::{FlexibleExtractor, MarkdownCodeBlockExtractor};
40pub use intent::{IntentError, IntentExtractor, PromptBasedExtractor};
41pub use multimodal::ImageData;
42pub use prompt::{PromptPart, PromptSetError, ToPrompt, ToPromptFor, ToPromptSet};
43
44use extract::ParseError;
45
46/// Extracts a JSON string from a raw LLM response string.
47///
48/// This function uses a `FlexibleExtractor` with its standard strategies
49/// to find and extract a JSON object from a string that may contain extraneous
50/// text, such as explanations or Markdown code blocks.
51///
52/// For more advanced control over extraction strategies, see the `extract::FlexibleExtractor` struct.
53///
54/// # Returns
55///
56/// A `Result` containing the extracted JSON `String` on success, or a `ParseError`
57/// if no JSON could be extracted.
58pub fn extract_json(text: &str) -> Result<String, ParseError> {
59    let extractor = FlexibleExtractor::new();
60    // Note: The standard strategies in the copied code are TaggedContent("answer"), JsonBrackets, FirstJsonObject.
61    // We will add a markdown strategy later during refactoring.
62    extractor.extract(text)
63}
64
65/// Extracts content from any Markdown code block in the text.
66///
67/// This function searches for the first code block (delimited by triple backticks)
68/// and returns its content. The code block can have any language specifier or none at all.
69///
70/// # Returns
71///
72/// A `Result` containing the extracted code block content on success, or a `ParseError`
73/// if no code block is found.
74pub fn extract_markdown_block(text: &str) -> Result<String, ParseError> {
75    let extractor = MarkdownCodeBlockExtractor::new();
76    extractor.extract(text)
77}
78
79/// Extracts content from a Markdown code block with a specific language.
80///
81/// This function searches for a code block with the specified language hint
82/// (e.g., ```rust, ```python) and returns its content.
83///
84/// # Arguments
85///
86/// * `text` - The text containing the markdown code block
87/// * `lang` - The language specifier to match (e.g., "rust", "python")
88///
89/// # Returns
90///
91/// A `Result` containing the extracted code block content on success, or a `ParseError`
92/// if no code block with the specified language is found.
93pub fn extract_markdown_block_with_lang(text: &str, lang: &str) -> Result<String, ParseError> {
94    let extractor = MarkdownCodeBlockExtractor::with_language(lang.to_string());
95    extractor.extract(text)
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn test_json_extraction() {
104        let input = "Some text before {\"key\": \"value\"} and after.";
105        assert_eq!(extract_json(input).unwrap(), "{\"key\": \"value\"}");
106    }
107
108    #[test]
109    fn test_standard_extraction_from_tagged_content() {
110        let text = "<answer>{\"type\": \"success\"}</answer>";
111        let result = extract_json(text);
112        assert!(result.is_ok());
113        assert_eq!(result.unwrap(), "{\"type\": \"success\"}");
114    }
115
116    #[test]
117    fn test_markdown_extraction() {
118        // Test simple code block with no language
119        let text1 = "Here is some code:\n```\nlet x = 42;\n```\nAnd some text after.";
120        let result1 = extract_markdown_block(text1);
121        assert!(result1.is_ok());
122        assert_eq!(result1.unwrap(), "let x = 42;");
123
124        // Test code block with specific language (rust)
125        let text2 = "Here's Rust code:\n```rust\nfn main() {
126    println!(\"Hello\");
127}
128```";
129        let result2 = extract_markdown_block_with_lang(text2, "rust");
130        assert!(result2.is_ok());
131        assert_eq!(result2.unwrap(), "fn main() {\n    println!(\"Hello\");\n}");
132
133        // Test extracting rust block when json block is also present
134        let text3 = r#"\nFirst a JSON block:
135```json
136{"key": "value"}
137```
138
139Then a Rust block:
140```rust
141let data = vec![1, 2, 3];
142```
143"#;
144        let result3 = extract_markdown_block_with_lang(text3, "rust");
145        assert!(result3.is_ok());
146        assert_eq!(result3.unwrap(), "let data = vec![1, 2, 3];");
147
148        // Test case where no code block is found
149        let text4 = "This text has no code blocks at all.";
150        let result4 = extract_markdown_block(text4);
151        assert!(result4.is_err());
152
153        // Test with messy surrounding text and newlines
154        let text5 = r#"\nLots of text before...
155
156
157   ```python
158def hello():
159    print("world")
160    return True
161   ```   
162
163
164And more text after with various spacing.
165"#;
166        let result5 = extract_markdown_block_with_lang(text5, "python");
167        assert!(result5.is_ok());
168        assert_eq!(
169            result5.unwrap(),
170            "def hello():\n    print(\"world\")\n    return True"
171        );
172    }
173}