Skip to main content

gemini_adk_rs/utils/
text.rs

1//! Small text helpers shared across the workspace: code-fence stripping,
2//! character-safe truncation, `{key}` templating and edit distance.
3
4use serde_json::Value;
5
6/// `text` without a surrounding Markdown code fence, for parsing the JSON a
7/// model wrapped in one.
8///
9/// Handles `` ```json\n…\n``` ``, a bare `` ```\n…\n``` ``, a fence on one
10/// line (`` ```{"a":1}``` ``), an unclosed fence, any language tag
11/// (`` ```JSON ``), and surrounding whitespace. Text with no fence comes back
12/// trimmed.
13///
14/// ```
15/// use gemini_adk_rs::utils::text::strip_code_fence;
16///
17/// assert_eq!(strip_code_fence("```json\n{\"a\": 1}\n```"), "{\"a\": 1}");
18/// assert_eq!(strip_code_fence("  {\"a\": 1}  "), "{\"a\": 1}");
19/// ```
20pub fn strip_code_fence(text: &str) -> &str {
21    let trimmed = text.trim();
22    let Some(rest) = trimmed.strip_prefix("```") else {
23        return trimmed;
24    };
25    let body = match rest.split_once('\n') {
26        // The opening line is only a language tag (or empty): drop it.
27        Some((tag, body)) if is_fence_tag(tag) => body,
28        // Content starts on the fence line: ```{"a":1}``` or ```json {"a":1}```.
29        _ => strip_json_tag(rest),
30    };
31    let body = body.trim_end();
32    body.strip_suffix("```").unwrap_or(body).trim()
33}
34
35/// Whether the text after an opening fence is just a language tag.
36fn is_fence_tag(tag: &str) -> bool {
37    tag.trim()
38        .chars()
39        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '+' | '.' | '#'))
40}
41
42/// Drop a leading `json` tag when the fence and the content share a line.
43fn strip_json_tag(rest: &str) -> &str {
44    match rest.get(..4) {
45        Some(tag)
46            if tag.eq_ignore_ascii_case("json")
47                && !rest[4..].starts_with(|c: char| c.is_ascii_alphanumeric()) =>
48        {
49            &rest[4..]
50        }
51        _ => rest,
52    }
53}
54
55/// The first `max_chars` characters of `s`, cut on a character boundary.
56///
57/// Unlike `&s[..n]`, this cannot panic on a multi-byte character.
58///
59/// ```
60/// use gemini_adk_rs::utils::text::truncate_chars;
61///
62/// assert_eq!(truncate_chars("héllo wörld", 5), "héllo");
63/// assert_eq!(truncate_chars("short", 50), "short");
64/// ```
65pub fn truncate_chars(s: &str, max_chars: usize) -> &str {
66    match s.char_indices().nth(max_chars) {
67        Some((i, _)) => &s[..i],
68        None => s,
69    }
70}
71
72/// `s`, or its first `max_chars` characters followed by `marker` when it is
73/// longer. The result is `max_chars` plus the marker at most.
74///
75/// ```
76/// use gemini_adk_rs::utils::text::truncate_with_marker;
77///
78/// assert_eq!(truncate_with_marker("héllo wörld", 5, "…"), "héllo…");
79/// assert_eq!(truncate_with_marker("héllo", 5, "…"), "héllo");
80/// ```
81pub fn truncate_with_marker(s: &str, max_chars: usize, marker: &str) -> String {
82    let head = truncate_chars(s, max_chars);
83    if head.len() == s.len() {
84        s.to_string()
85    } else {
86        format!("{head}{marker}")
87    }
88}
89
90/// Replace each `{expr}` in `template` with the value `lookup` gives for
91/// `expr` (trimmed): a string verbatim, any other JSON value as its JSON
92/// text. An unknown `expr` becomes the empty string; an unclosed `{` is kept
93/// as written.
94///
95/// The scanner is shared; what `expr` means is the caller's. `Orchestration`
96/// looks it up as a state key, the spec layer reads `args.` and `state.`
97/// prefixes.
98///
99/// ```
100/// use gemini_adk_rs::utils::text::interpolate_with;
101/// use serde_json::json;
102///
103/// let out = interpolate_with("hi {name}, n={n}, {gone}!", |key| match key {
104///     "name" => Some(json!("Ada")),
105///     "n" => Some(json!(3)),
106///     _ => None,
107/// });
108/// assert_eq!(out, "hi Ada, n=3, !");
109/// ```
110pub fn interpolate_with(template: &str, mut lookup: impl FnMut(&str) -> Option<Value>) -> String {
111    let mut out = String::with_capacity(template.len());
112    let mut rest = template;
113    while let Some(open) = rest.find('{') {
114        out.push_str(&rest[..open]);
115        let after = &rest[open + 1..];
116        let Some(close) = after.find('}') else {
117            out.push_str(&rest[open..]);
118            return out;
119        };
120        match lookup(after[..close].trim()) {
121            Some(Value::String(s)) => out.push_str(&s),
122            Some(v) => out.push_str(&v.to_string()),
123            None => {}
124        }
125        rest = &after[close + 1..];
126    }
127    out.push_str(rest);
128    out
129}
130
131/// Edit distance between `a` and `b`, counted in characters (insert, delete
132/// and substitute each cost 1).
133///
134/// ```
135/// use gemini_adk_rs::utils::text::levenshtein;
136///
137/// assert_eq!(levenshtein("kitten", "sitting"), 3);
138/// assert_eq!(levenshtein("héllo", "hello"), 1);
139/// ```
140pub fn levenshtein(a: &str, b: &str) -> usize {
141    strsim::levenshtein(a, b)
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147    use serde_json::json;
148
149    #[test]
150    fn fence_with_a_json_tag() {
151        assert_eq!(strip_code_fence("```json\n{\"a\": 1}\n```"), "{\"a\": 1}");
152        assert_eq!(strip_code_fence("```JSON\n{\"a\": 1}\n```"), "{\"a\": 1}");
153        assert_eq!(
154            strip_code_fence("```json\r\n{\"a\": 1}\r\n```"),
155            "{\"a\": 1}"
156        );
157    }
158
159    #[test]
160    fn bare_fence() {
161        assert_eq!(strip_code_fence("```\n{\"a\": 1}\n```"), "{\"a\": 1}");
162        assert_eq!(strip_code_fence("```\n[1, 2]\n```"), "[1, 2]");
163    }
164
165    #[test]
166    fn no_fence() {
167        assert_eq!(strip_code_fence("{\"a\": 1}"), "{\"a\": 1}");
168        assert_eq!(strip_code_fence("plain words"), "plain words");
169        assert_eq!(strip_code_fence(""), "");
170    }
171
172    #[test]
173    fn surrounding_whitespace() {
174        assert_eq!(strip_code_fence("  \n{\"a\": 1}\n  "), "{\"a\": 1}");
175        assert_eq!(
176            strip_code_fence("\n\n  ```json\n  {\"a\": 1}  \n```  \n\n"),
177            "{\"a\": 1}"
178        );
179    }
180
181    #[test]
182    fn single_line_and_unclosed_fences() {
183        assert_eq!(strip_code_fence("```{\"a\": 1}```"), "{\"a\": 1}");
184        assert_eq!(strip_code_fence("```json{\"a\": 1}```"), "{\"a\": 1}");
185        assert_eq!(strip_code_fence("```json {\"a\": 1}```"), "{\"a\": 1}");
186        assert_eq!(strip_code_fence("```json\n{\"a\": 1}"), "{\"a\": 1}");
187        // A value that merely starts with the letters of a tag is content.
188        assert_eq!(strip_code_fence("```jsonish```"), "jsonish");
189        // A fence whose first line is content, not a tag, keeps that line.
190        assert_eq!(strip_code_fence("```{\n\"a\": 1\n}\n```"), "{\n\"a\": 1\n}");
191    }
192
193    #[test]
194    fn truncate_chars_cuts_on_a_character_boundary() {
195        // 'é' is two bytes and '日' three: a byte slice at 2 or 4 would panic.
196        let s = "é日本語です";
197        assert_eq!(truncate_chars(s, 2), "é日");
198        assert_eq!(truncate_chars(s, 0), "");
199        assert_eq!(truncate_chars(s, 6), s);
200        assert_eq!(truncate_chars(s, 100), s);
201        assert_eq!(truncate_chars("", 3), "");
202    }
203
204    #[test]
205    fn truncate_with_marker_marks_only_a_cut() {
206        let s = "日本語のテキスト";
207        assert_eq!(truncate_with_marker(s, 3, "..."), "日本語...");
208        assert_eq!(truncate_with_marker(s, 8, "..."), s);
209        assert_eq!(truncate_with_marker("abc", 2, "…"), "ab…");
210    }
211
212    /// The CLI's old byte-slicing `truncate` (`&s[..max - 3]` with max 80)
213    /// panicked here: byte 77 falls inside a three-byte character.
214    #[test]
215    fn a_multibyte_string_that_byte_slicing_would_have_panicked_on() {
216        let s = "日".repeat(100); // 300 bytes
217        assert!(!s.is_char_boundary(77));
218        let cut = truncate_with_marker(&s, 77, "...");
219        assert_eq!(cut.chars().count(), 80);
220        assert!(cut.ends_with("日..."));
221    }
222
223    #[test]
224    fn interpolate_with_substitutes_strings_and_json() {
225        let out = interpolate_with("a {x} b {n} c {obj} d {gone}.", |k| match k {
226            "x" => Some(json!("X")),
227            "n" => Some(json!(7)),
228            "obj" => Some(json!({"k": 1})),
229            _ => None,
230        });
231        assert_eq!(out, "a X b 7 c {\"k\":1} d .");
232    }
233
234    #[test]
235    fn interpolate_with_trims_keys_and_keeps_an_unclosed_brace() {
236        let out = interpolate_with("{ k } and {oops", |k| {
237            assert_eq!(k, "k");
238            Some(json!("v"))
239        });
240        assert_eq!(out, "v and {oops");
241        assert_eq!(interpolate_with("no braces", |_| None), "no braces");
242    }
243
244    #[test]
245    fn levenshtein_counts_characters_not_bytes() {
246        assert_eq!(levenshtein("", ""), 0);
247        assert_eq!(levenshtein("abc", ""), 3);
248        assert_eq!(levenshtein("kitten", "sitting"), 3);
249        assert_eq!(levenshtein("héllo", "hello"), 1);
250        assert_eq!(levenshtein("日本語", "日本"), 1);
251    }
252}