Skip to main content

rs_adk/code_executors/
utils.rs

1use rs_genai::prelude::{CodeExecutionResult as GenaiCodeExecResult, ExecutableCode, Part};
2
3/// Extract the first code block from text content using the given delimiters.
4///
5/// Returns `Some((code, remaining_text))` where `code` is the extracted code
6/// and `remaining_text` is the original text with the code block removed.
7/// Returns `None` if no code block is found.
8pub fn extract_code_from_text(
9    text: &str,
10    delimiters: &[(String, String)],
11) -> Option<(String, String)> {
12    for (start_delim, end_delim) in delimiters {
13        if let Some(start_idx) = text.find(start_delim.as_str()) {
14            let code_start = start_idx + start_delim.len();
15            if let Some(end_idx) = text[code_start..].find(end_delim.as_str()) {
16                let code = text[code_start..code_start + end_idx].to_string();
17                let remaining = format!(
18                    "{}{}",
19                    &text[..start_idx],
20                    &text[code_start + end_idx + end_delim.len()..]
21                );
22                return Some((code, remaining));
23            }
24        }
25    }
26    None
27}
28
29/// Build an `ExecutableCode` Part (language=PYTHON).
30pub fn build_executable_code_part(code: &str) -> Part {
31    Part::ExecutableCode {
32        executable_code: ExecutableCode {
33            language: "PYTHON".to_string(),
34            code: code.to_string(),
35        },
36    }
37}
38
39/// Build a `CodeExecutionResult` Part with OK or FAILED outcome.
40///
41/// If `stderr` is empty the outcome is "OK" and the output is `stdout`.
42/// Otherwise the outcome is "FAILED" and the output combines both streams.
43pub fn build_code_execution_result_part(stdout: &str, stderr: &str) -> Part {
44    let outcome = if stderr.is_empty() { "OK" } else { "FAILED" };
45    let output = if stderr.is_empty() {
46        stdout.to_string()
47    } else {
48        format!("{}\n{}", stdout, stderr)
49    };
50    Part::CodeExecutionResult {
51        code_execution_result: GenaiCodeExecResult {
52            outcome: outcome.to_string(),
53            output: Some(output),
54        },
55    }
56}