llm_toolkit/extract/
extractors.rs1use super::core::{ContentExtractor, ExtractionStrategy};
2
3use super::error::ParseError;
4use log::debug;
5use regex::Regex;
6
7pub struct FlexibleExtractor {
9 debug_mode: bool,
10}
11
12impl FlexibleExtractor {
13 pub fn new() -> Self {
14 Self { debug_mode: false }
15 }
16
17 pub fn with_debug(mut self) -> Self {
18 self.debug_mode = true;
19 self
20 }
21
22 pub fn standard_extraction_strategies() -> Vec<ExtractionStrategy> {
23 vec![
24 ExtractionStrategy::TaggedContent("answer".to_string()),
25 ExtractionStrategy::JsonBrackets,
26 ExtractionStrategy::FirstJsonObject,
27 ]
28 }
29
30 pub fn extract(&self, text: &str) -> Result<String, ParseError> {
32 if self.debug_mode {
33 debug!("Extracting content from text: {}", text);
34 }
35 self.extract_with_strategies(text, &Self::standard_extraction_strategies())
36 }
37
38 pub fn extract_with_strategy(
40 &self,
41 text: &str,
42 strategy: &ExtractionStrategy,
43 ) -> Option<String> {
44 if self.debug_mode {
45 debug!("Trying extraction strategy: {:?}", strategy);
46 }
47
48 match strategy {
49 ExtractionStrategy::TaggedContent(tag) => self.extract_tagged(text, tag),
50 ExtractionStrategy::JsonBrackets => self.extract_json_like(text),
51 ExtractionStrategy::FirstJsonObject => self.extract_first_json_object(text),
52 ExtractionStrategy::KeywordSearch(keywords) => self.extract_by_keywords(text, keywords),
53 ExtractionStrategy::RegexPattern(pattern) => self.extract_pattern(text, pattern),
54 ExtractionStrategy::OriginalText => Some(text.to_string()),
55 }
56 }
57
58 pub fn extract_with_strategies(
60 &self,
61 text: &str,
62 strategies: &[ExtractionStrategy],
63 ) -> Result<String, ParseError> {
64 let mut errors = Vec::new();
65
66 for strategy in strategies {
67 if let Some(result) = self.extract_with_strategy(text, strategy) {
68 if self.debug_mode {
69 debug!("Successfully extracted with strategy: {:?}", strategy);
70 }
71 return Ok(result);
72 } else {
73 errors.push(format!("Strategy {:?} failed", strategy));
74 }
75 }
76
77 Err(ParseError::AllStrategiesFailed(errors))
78 }
79
80 fn extract_first_json_object(&self, text: &str) -> Option<String> {
82 let mut brace_count = 0;
83 let mut start_pos = None;
84 let mut in_string = false;
85 let mut escape_next = false;
86
87 for (i, ch) in text.char_indices() {
88 if escape_next {
89 escape_next = false;
90 continue;
91 }
92
93 match ch {
94 '\\' if in_string => escape_next = true,
95 '"' => in_string = !in_string,
96 '{' if !in_string => {
97 if brace_count == 0 {
98 start_pos = Some(i);
99 }
100 brace_count += 1;
101 }
102 '}' if !in_string => {
103 brace_count -= 1;
104 if brace_count == 0
105 && let Some(p) = start_pos
106 {
107 return Some(text[p..=i].to_string());
108 }
109 }
110 _ => {}
111 }
112 }
113
114 None
115 }
116
117 fn extract_by_keywords(&self, text: &str, keywords: &[String]) -> Option<String> {
119 let lower_text = text.to_lowercase();
120
121 for keyword in keywords {
122 if lower_text.contains(&keyword.to_lowercase()) {
123 return Some(keyword.clone());
125 }
126 }
127
128 None
129 }
130}
131
132impl Default for FlexibleExtractor {
133 fn default() -> Self {
134 Self::new()
135 }
136}
137
138impl ContentExtractor for FlexibleExtractor {
139 fn extract_tagged(&self, text: &str, tag: &str) -> Option<String> {
140 let pattern = format!(r"(?s)<{tag}>(.*?)</{tag}>", tag = regex::escape(tag));
142
143 if let Ok(regex) = Regex::new(&pattern)
144 && let Some(captures) = regex.captures(text)
145 && let Some(content) = captures.get(1)
146 {
147 return Some(content.as_str().trim().to_string());
148 }
149
150 if self.debug_mode {
151 debug!("Failed to extract tagged content with tag: {}", tag);
152 }
153
154 None
155 }
156
157 fn extract_json_like(&self, text: &str) -> Option<String> {
158 if let Some(start) = text.find('{')
160 && let Some(end) = text.rfind('}')
161 && end > start
162 {
163 return Some(text[start..=end].to_string());
164 }
165
166 if self.debug_mode {
167 debug!("Failed to extract JSON-like content");
168 }
169
170 None
171 }
172
173 fn extract_pattern(&self, text: &str, pattern: &str) -> Option<String> {
174 if let Ok(regex) = Regex::new(pattern)
175 && let Some(captures) = regex.captures(text)
176 {
177 if captures.len() > 1 {
179 return captures.get(1).map(|m| m.as_str().to_string());
180 } else {
181 return captures.get(0).map(|m| m.as_str().to_string());
182 }
183 }
184
185 if self.debug_mode {
186 debug!("Failed to extract with pattern: {}", pattern);
187 }
188
189 None
190 }
191}
192
193pub struct MarkdownCodeBlockExtractor {
195 pub language: Option<String>,
197}
198
199impl Default for MarkdownCodeBlockExtractor {
200 fn default() -> Self {
201 Self::new()
202 }
203}
204
205impl MarkdownCodeBlockExtractor {
206 pub fn new() -> Self {
208 Self { language: None }
209 }
210
211 pub fn with_language(language: String) -> Self {
213 Self {
214 language: Some(language),
215 }
216 }
217
218 pub fn extract(&self, text: &str) -> Result<String, ParseError> {
220 let pattern = if let Some(ref lang) = self.language {
221 format!(
223 r"(?m)^\s*```\s*{}\s*\n((?:.*\n)*?)^\s*```\s*$",
224 regex::escape(lang)
225 )
226 } else {
227 r"(?m)^\s*```[^\n]*\n((?:.*\n)*?)^\s*```\s*$".to_string()
229 };
230
231 let regex = Regex::new(&pattern)
232 .map_err(|e| ParseError::InvalidFormat(format!("Failed to compile regex: {}", e)))?;
233
234 if let Some(captures) = regex.captures(text)
235 && let Some(content) = captures.get(1)
236 {
237 let extracted = content.as_str().trim_end();
239 return Ok(extracted.to_string());
240 }
241
242 Err(ParseError::TagExtractionFailed(format!(
243 "No markdown code block found{}",
244 if let Some(ref lang) = self.language {
245 format!(" with language '{}'", lang)
246 } else {
247 String::new()
248 }
249 )))
250 }
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256
257 #[test]
258 fn test_extract_tagged_content() {
259 let extractor = FlexibleExtractor::new();
260
261 let text = "<answer>Hello World</answer>";
262 let result = extractor.extract_tagged(text, "answer");
263 assert_eq!(result, Some("Hello World".to_string()));
264
265 let text_with_whitespace = "<answer>\n Hello World \n</answer>";
266 let result = extractor.extract_tagged(text_with_whitespace, "answer");
267 assert_eq!(result, Some("Hello World".to_string()));
268 }
269
270 #[test]
271 fn test_extract_json_like() {
272 let extractor = FlexibleExtractor::new();
273
274 let text = "Here is some JSON: {\"key\": \"value\"} and more text";
275 let result = extractor.extract_json_like(text);
276 assert_eq!(result, Some("{\"key\": \"value\"}".to_string()));
277 }
278
279 #[test]
280 fn test_extract_first_json_object() {
281 let extractor = FlexibleExtractor::new();
282
283 let text = "Some text {\"first\": \"object\"} more text {\"second\": \"object\"}";
284 let result = extractor.extract_first_json_object(text);
285 assert_eq!(result, Some("{\"first\": \"object\"}".to_string()));
286 }
287
288 #[test]
289 fn test_extract_by_keywords() {
290 let extractor = FlexibleExtractor::new();
291 let keywords = vec!["Comfort".to_string(), "Debug".to_string()];
292
293 let text = "This is about comfort and support";
294 let result = extractor.extract_by_keywords(text, &keywords);
295 assert_eq!(result, Some("Comfort".to_string()));
296 }
297
298 #[test]
299 fn test_extraction_strategies() {
300 let extractor = FlexibleExtractor::new();
301
302 let strategies = vec![
303 ExtractionStrategy::TaggedContent("answer".to_string()),
304 ExtractionStrategy::JsonBrackets,
305 ExtractionStrategy::OriginalText,
306 ];
307
308 let text = "<answer>{\"type\": \"success\"}</answer>";
309 let result = extractor.extract_with_strategies(text, &strategies);
310 assert!(result.is_ok());
311 assert_eq!(result.unwrap(), "{\"type\": \"success\"}");
312 }
313}