alith_client/primitives/
text.rs

1use super::PrimitiveTrait;
2use crate::components::grammar::{Grammar, TextGrammar};
3use anyhow::Result;
4pub struct TextPrimitive {
5    pub text_token_length: u32,
6    pub disallowed_chars: Vec<char>,
7    pub allow_newline: bool,
8}
9
10impl Default for TextPrimitive {
11    fn default() -> Self {
12        TextPrimitive {
13            text_token_length: 200,
14            disallowed_chars: vec![],
15            allow_newline: false,
16        }
17    }
18}
19
20impl TextPrimitive {
21    pub fn text_token_length(&mut self, text_token_length: u32) -> &mut Self {
22        self.text_token_length = text_token_length;
23        self
24    }
25
26    pub fn disallowed_char(&mut self, disallowed_char: char) -> &mut Self {
27        self.disallowed_chars.push(disallowed_char);
28        self
29    }
30
31    pub fn disallowed_chars(&mut self, disallowed_chars: Vec<char>) -> &mut Self {
32        self.disallowed_chars.extend(disallowed_chars);
33        self
34    }
35
36    pub fn allow_newline(&mut self, allow_newline: bool) -> &mut Self {
37        self.allow_newline = allow_newline;
38        self
39    }
40
41    fn grammar_inner(&self) -> TextGrammar {
42        Grammar::text()
43            .item_token_length(self.text_token_length)
44            .disallowed_chars(self.disallowed_chars.clone())
45            .allow_newline(self.allow_newline)
46    }
47}
48
49impl PrimitiveTrait for TextPrimitive {
50    type PrimitiveResult = String;
51
52    fn clear_primitive(&mut self) {}
53
54    fn type_description(&self, result_can_be_none: bool) -> &str {
55        if result_can_be_none {
56            "text or 'None.'"
57        } else {
58            "text"
59        }
60    }
61
62    fn solution_description(&self, result_can_be_none: bool) -> String {
63        if result_can_be_none {
64            "text or 'None.'".to_string()
65        } else {
66            "text".to_string()
67        }
68    }
69
70    fn stop_word_result_is_none(&self, result_can_be_none: bool) -> Option<String> {
71        if result_can_be_none {
72            Some("None.".to_string())
73        } else {
74            None
75        }
76    }
77
78    fn grammar(&self) -> Grammar {
79        self.grammar_inner().wrap()
80    }
81
82    fn parse_to_primitive(&self, content: &str) -> Result<Self::PrimitiveResult> {
83        let parsed: Self::PrimitiveResult = self.grammar_inner().grammar_parse(content)?;
84        Ok(parsed)
85    }
86}