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// Allow the crate to reference itself by name, which is needed for proc macros
10// to work correctly in examples, tests, and bins
11extern crate self as llm_toolkit;
12
13/// A derive macro to implement the `ToPrompt` trait for structs.
14///
15/// This macro is available only when the `derive` feature is enabled.
16/// See the [crate-level documentation](index.html#2-structured-prompts-with-derivetoprompt) for usage examples.
17#[cfg(feature = "derive")]
18pub use llm_toolkit_macros::ToPrompt;
19
20/// A derive macro to implement the `ToPromptSet` trait for structs.
21///
22/// This macro is available only when the `derive` feature is enabled.
23#[cfg(feature = "derive")]
24pub use llm_toolkit_macros::ToPromptSet;
25
26/// A derive macro to implement the `ToPromptFor` trait for structs.
27///
28/// This macro is available only when the `derive` feature is enabled.
29#[cfg(feature = "derive")]
30pub use llm_toolkit_macros::ToPromptFor;
31
32/// A macro for creating examples sections in prompts.
33///
34/// This macro is available only when the `derive` feature is enabled.
35#[cfg(feature = "derive")]
36pub use llm_toolkit_macros::examples_section;
37
38/// A procedural attribute macro for defining intent enums with automatic prompt and extractor generation.
39///
40/// This macro is available only when the `derive` feature is enabled.
41#[cfg(feature = "derive")]
42pub use llm_toolkit_macros::define_intent;
43
44/// A derive macro to implement the `Agent` trait for structs.
45///
46/// This macro is available only when the `agent` feature is enabled.
47/// It automatically generates an Agent implementation that uses ClaudeCodeAgent
48/// internally and deserializes responses into a structured output type.
49///
50/// # Example
51///
52/// ```ignore
53/// use llm_toolkit_macros::Agent;
54/// use serde::{Deserialize, Serialize};
55///
56/// #[derive(Serialize, Deserialize)]
57/// struct MyOutput {
58///     result: String,
59/// }
60///
61/// #[derive(Agent)]
62/// #[agent(expertise = "My expertise", output = "MyOutput")]
63/// struct MyAgent;
64/// ```
65#[cfg(feature = "agent")]
66pub use llm_toolkit_macros::Agent;
67
68/// An attribute macro to define agent structs with automatic trait implementations.
69///
70/// This macro is available only when the `agent` feature is enabled.
71#[cfg(feature = "agent")]
72pub use llm_toolkit_macros::agent;
73
74pub mod extract;
75pub mod intent;
76pub mod multimodal;
77pub mod prompt;
78
79#[cfg(feature = "agent")]
80pub mod agent;
81
82#[cfg(feature = "agent")]
83pub mod orchestrator;
84
85pub use extract::{FlexibleExtractor, MarkdownCodeBlockExtractor};
86pub use intent::frame::IntentFrame;
87#[allow(deprecated)]
88pub use intent::{IntentError, IntentExtractor, PromptBasedExtractor};
89pub use multimodal::ImageData;
90pub use prompt::{PromptPart, PromptSetError, ToPrompt, ToPromptFor, ToPromptSet};
91
92#[cfg(feature = "agent")]
93pub use agent::{Agent, AgentError};
94
95#[cfg(feature = "agent")]
96pub use orchestrator::{BlueprintWorkflow, Orchestrator, OrchestratorError, StrategyMap};
97
98use extract::ParseError;
99
100/// Extracts a JSON string from a raw LLM response string.
101///
102/// This function uses a `FlexibleExtractor` with its standard strategies
103/// to find and extract a JSON object from a string that may contain extraneous
104/// text, such as explanations or Markdown code blocks.
105///
106/// For more advanced control over extraction strategies, see the `extract::FlexibleExtractor` struct.
107///
108/// # Returns
109///
110/// A `Result` containing the extracted JSON `String` on success, or a `ParseError`
111/// if no JSON could be extracted.
112pub fn extract_json(text: &str) -> Result<String, ParseError> {
113    let extractor = FlexibleExtractor::new();
114    // Note: The standard strategies in the copied code are TaggedContent("answer"), JsonBrackets, FirstJsonObject.
115    // We will add a markdown strategy later during refactoring.
116    extractor.extract(text)
117}
118
119/// Extracts content from any Markdown code block in the text.
120///
121/// This function searches for the first code block (delimited by triple backticks)
122/// and returns its content. The code block can have any language specifier or none at all.
123///
124/// # Returns
125///
126/// A `Result` containing the extracted code block content on success, or a `ParseError`
127/// if no code block is found.
128pub fn extract_markdown_block(text: &str) -> Result<String, ParseError> {
129    let extractor = MarkdownCodeBlockExtractor::new();
130    extractor.extract(text)
131}
132
133/// Extracts content from a Markdown code block with a specific language.
134///
135/// This function searches for a code block with the specified language hint
136/// (e.g., ```rust, ```python) and returns its content.
137///
138/// # Arguments
139///
140/// * `text` - The text containing the markdown code block
141/// * `lang` - The language specifier to match (e.g., "rust", "python")
142///
143/// # Returns
144///
145/// A `Result` containing the extracted code block content on success, or a `ParseError`
146/// if no code block with the specified language is found.
147pub fn extract_markdown_block_with_lang(text: &str, lang: &str) -> Result<String, ParseError> {
148    let extractor = MarkdownCodeBlockExtractor::with_language(lang.to_string());
149    extractor.extract(text)
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn test_json_extraction() {
158        let input = "Some text before {\"key\": \"value\"} and after.";
159        assert_eq!(extract_json(input).unwrap(), "{\"key\": \"value\"}");
160    }
161
162    #[test]
163    fn test_standard_extraction_from_tagged_content() {
164        let text = "<answer>{\"type\": \"success\"}</answer>";
165        let result = extract_json(text);
166        assert!(result.is_ok());
167        assert_eq!(result.unwrap(), "{\"type\": \"success\"}");
168    }
169
170    #[test]
171    fn test_markdown_extraction() {
172        // Test simple code block with no language
173        let text1 = "Here is some code:\n```\nlet x = 42;\n```\nAnd some text after.";
174        let result1 = extract_markdown_block(text1);
175        assert!(result1.is_ok());
176        assert_eq!(result1.unwrap(), "let x = 42;");
177
178        // Test code block with specific language (rust)
179        let text2 = "Here's Rust code:\n```rust\nfn main() {
180    println!(\"Hello\");
181}
182```";
183        let result2 = extract_markdown_block_with_lang(text2, "rust");
184        assert!(result2.is_ok());
185        assert_eq!(result2.unwrap(), "fn main() {\n    println!(\"Hello\");\n}");
186
187        // Test extracting rust block when json block is also present
188        let text3 = r#"\nFirst a JSON block:
189```json
190{"key": "value"}
191```
192
193Then a Rust block:
194```rust
195let data = vec![1, 2, 3];
196```
197"#;
198        let result3 = extract_markdown_block_with_lang(text3, "rust");
199        assert!(result3.is_ok());
200        assert_eq!(result3.unwrap(), "let data = vec![1, 2, 3];");
201
202        // Test case where no code block is found
203        let text4 = "This text has no code blocks at all.";
204        let result4 = extract_markdown_block(text4);
205        assert!(result4.is_err());
206
207        // Test with messy surrounding text and newlines
208        let text5 = r#"\nLots of text before...
209
210
211   ```python
212def hello():
213    print("world")
214    return True
215   ```   
216
217
218And more text after with various spacing.
219"#;
220        let result5 = extract_markdown_block_with_lang(text5, "python");
221        assert!(result5.is_ok());
222        assert_eq!(
223            result5.unwrap(),
224            "def hello():\n    print(\"world\")\n    return True"
225        );
226    }
227}