Skip to main content

codetether_rlm/router/
extract.rs

1//! FINAL extraction from LLM text responses.
2
3/// Extract the answer from a `FINAL("…")` call in LLM text.
4pub fn extract_final(text: &str) -> Option<String> {
5    let start_idx = text.find("FINAL")?;
6    let after = &text[start_idx..];
7    let open_idx = after.find(['"', '\'', '`'])?;
8    let quote_char = after[open_idx..].chars().next()?;
9    let content_start = start_idx + open_idx + quote_char.len_utf8();
10    let content = &text[content_start..];
11    let close_idx = content.find(quote_char)?;
12    let answer = &content[..close_idx];
13    (!answer.is_empty()).then(|| answer.to_string())
14}
15
16#[cfg(test)]
17mod tests {
18    use super::*;
19
20    #[test]
21    fn extracts_double_quoted() {
22        assert_eq!(
23            extract_final(r#"Some text FINAL("the answer") more"#),
24            Some("the answer".into())
25        );
26    }
27
28    #[test]
29    fn extracts_single_quoted() {
30        assert_eq!(extract_final("text FINAL('ans') x"), Some("ans".into()));
31    }
32
33    #[test]
34    fn empty_answer_is_none() {
35        assert_eq!(extract_final(r#"FINAL("")"#), None);
36    }
37
38    #[test]
39    fn no_final_is_none() {
40        assert_eq!(extract_final("just text"), None);
41    }
42}