Skip to main content

strands/vended_tools/
python_repl.rs

1//! The sandbox-routed `python_repl` tool.
2//!
3//! Each call pipes the code to a fresh interpreter in the sandbox, so variables, imports and
4//! definitions do not persist across calls; files written to the sandbox do.
5
6use std::sync::Arc;
7
8use serde::Serialize;
9use serde_json::json;
10
11use super::input::InputReader;
12use super::{js_number_text, resolve_sandbox, seconds, tool_error};
13use crate::cancel::CancelSignal;
14use crate::error::{Error, Result, SandboxTimeoutError};
15use crate::sandbox::{ExecuteOptions, Sandbox, is_valid_language};
16use crate::tools::{FunctionTool, ToolError};
17use crate::types::{JsonSchema, JsonValue};
18
19const DEFAULT_LANGUAGE: &str = "python3";
20const DEFAULT_TIMEOUT: f64 = 120.0;
21
22/// The description of the `python_repl` tool shown to the model (`PYTHON_REPL_DESCRIPTION`).
23pub const PYTHON_REPL_DESCRIPTION: &str = concat!(
24    "Executes Python code and returns output (stdout), error (stderr), and exit_code (non-zero means the ",
25    "code failed). Each call runs in a fresh interpreter; variables, imports, and definitions do not persist ",
26    "across calls. Files written to the working directory persist while the sandbox is alive, so save ",
27    "intermediate results to files when later calls need them. stdin is not available (input() fails). ",
28    "Use print() to surface values."
29);
30
31tool_error!(
32    /// The sandbox failed to run the code (`PythonReplError`), for example an unreachable
33    /// container. Errors in the code itself are results with `error` and a non-zero
34    /// `exit_code`.
35    PythonReplError
36);
37
38/// What the interpreter produced (`PythonReplOutput`).
39#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
40#[non_exhaustive]
41pub struct PythonReplOutput {
42    /// Standard output.
43    pub output: String,
44    /// Standard error, including tracebacks; empty when there was none.
45    pub error: String,
46    /// The interpreter's exit code; non-zero means the code failed, and 124 that it timed out.
47    pub exit_code: i32,
48}
49
50impl PythonReplOutput {
51    /// Creates an output.
52    pub fn new(output: impl Into<String>, error: impl Into<String>, exit_code: i32) -> Self {
53        Self {
54            output: output.into(),
55            error: error.into(),
56            exit_code,
57        }
58    }
59}
60
61/// The code exceeded its timeout: the sandbox's [`SandboxTimeoutError`] (the
62/// [`source`](std::error::Error::source)) with the partial output appended to the message as
63/// JSON with exit code 124, because the model sees only the message.
64#[derive(Debug, Clone, PartialEq, thiserror::Error)]
65#[error("{message}")]
66#[non_exhaustive]
67pub struct PythonReplTimeoutError {
68    message: String,
69    /// The output captured before the interpreter was killed.
70    pub partial: PythonReplOutput,
71    #[source]
72    timeout: SandboxTimeoutError,
73}
74
75impl PythonReplTimeoutError {
76    fn new(timeout: SandboxTimeoutError) -> Result<Self> {
77        let partial = PythonReplOutput::new(timeout.stdout.clone(), timeout.stderr.clone(), 124);
78        let message = format!("{timeout}\n{}", serde_json::to_string(&partial)?);
79        Ok(Self {
80            message,
81            partial,
82            timeout,
83        })
84    }
85
86    /// What failed.
87    #[must_use]
88    pub fn message(&self) -> &str {
89        &self.message
90    }
91
92    /// The sandbox's timeout error.
93    #[must_use]
94    pub fn timeout(&self) -> &SandboxTimeoutError {
95        &self.timeout
96    }
97}
98
99/// Options for [`make_python_repl`] (`MakePythonReplOptions`).
100#[derive(Clone, Default, bon::Builder)]
101#[builder(on(String, into))]
102pub struct MakePythonReplOptions {
103    /// The sandbox to run in. `None` uses the calling agent's
104    /// [`sandbox`](crate::ToolAgent::sandbox).
105    pub sandbox: Option<Arc<dyn Sandbox>>,
106    /// The tool name; `python_repl` when absent.
107    pub name: Option<String>,
108    /// The tool description; [`PYTHON_REPL_DESCRIPTION`] when absent.
109    pub description: Option<String>,
110    /// The interpreter that runs the code; `python3` when absent.
111    pub language: Option<String>,
112}
113
114impl std::fmt::Debug for MakePythonReplOptions {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        f.debug_struct("MakePythonReplOptions")
117            .field("sandbox", &self.sandbox.is_some())
118            .field("name", &self.name)
119            .field("language", &self.language)
120            .finish_non_exhaustive()
121    }
122}
123
124fn input_schema() -> JsonSchema {
125    json!({
126        "type": "object",
127        "properties": {
128            "code": {"type": "string", "description": "Python source to execute."},
129            "timeout": {
130                "description": "Timeout in seconds (default: 120). Must be positive.",
131                "type": "number",
132                "exclusiveMinimum": 0
133            }
134        },
135        "required": ["code"],
136        "additionalProperties": false
137    })
138}
139
140/// The default `python_repl` tool, running in the calling agent's sandbox.
141#[must_use]
142pub fn python_repl() -> FunctionTool {
143    build(
144        None,
145        "python_repl".to_owned(),
146        PYTHON_REPL_DESCRIPTION.to_owned(),
147        DEFAULT_LANGUAGE.to_owned(),
148    )
149}
150
151/// Creates a sandbox-routed Python tool: it runs `code` with the sandbox's
152/// [`execute_code`](Sandbox::execute_code) and returns a [`PythonReplOutput`] as JSON.
153///
154/// A timeout fails with a [`PythonReplTimeoutError`], cancellation with the sandbox's
155/// [`SandboxAbortError`](crate::SandboxAbortError) with the partial output appended to its
156/// message as JSON with exit code 130, and any other sandbox failure with a [`PythonReplError`].
157///
158/// ```
159/// use strands::vended_tools::python_repl::{MakePythonReplOptions, make_python_repl};
160///
161/// let tool = make_python_repl(MakePythonReplOptions::builder().language("python3.12").build())?;
162/// assert_eq!(strands::Tool::name(&tool), "python_repl");
163/// # Ok::<(), strands::Error>(())
164/// ```
165///
166/// # Errors
167///
168/// When `name` is empty or `language` does not match
169/// [`LANGUAGE_PATTERN`](crate::sandbox::LANGUAGE_PATTERN).
170pub fn make_python_repl(options: MakePythonReplOptions) -> Result<FunctionTool> {
171    let name = options.name.unwrap_or_else(|| "python_repl".to_owned());
172    let language = options.language.unwrap_or_else(|| DEFAULT_LANGUAGE.to_owned());
173    if name.is_empty() {
174        return Err(Error::other("name must be a non-empty string"));
175    }
176    if !is_valid_language(&language) {
177        return Err(Error::other(format!(
178            "language contains invalid characters: {language}"
179        )));
180    }
181    let description = options
182        .description
183        .unwrap_or_else(|| PYTHON_REPL_DESCRIPTION.to_owned());
184    Ok(build(options.sandbox, name, description, language))
185}
186
187fn build(bound: Option<Arc<dyn Sandbox>>, name: String, description: String, language: String) -> FunctionTool {
188    let language = Arc::new(language);
189    FunctionTool::builder(name, description)
190        .input_schema(input_schema())
191        .callback(move |input, context| {
192            let sandbox = resolve_sandbox(bound.as_ref(), &context);
193            let signal = context.cancel_signal().clone();
194            let language = language.clone();
195            async move { run(sandbox.as_ref(), &input, &language, signal).await }
196        })
197}
198
199async fn run(
200    sandbox: &dyn Sandbox,
201    input: &JsonValue,
202    language: &str,
203    signal: CancelSignal,
204) -> std::result::Result<JsonValue, ToolError> {
205    let mut reader = InputReader::new(input);
206    let code = reader.string("code");
207    let timeout = reader.optional_positive("timeout", |value| {
208        format!(
209            "timeout must be a positive number of seconds, got {}",
210            js_number_text(value)
211        )
212    });
213    reader.finish()?;
214    let options = ExecuteOptions {
215        timeout: seconds(timeout.unwrap_or(DEFAULT_TIMEOUT)),
216        signal: Some(signal),
217        ..ExecuteOptions::default()
218    };
219    match sandbox.execute_code(code.unwrap_or_default(), language, options).await {
220        Ok(result) => Ok(serde_json::to_value(PythonReplOutput::new(
221            result.stdout,
222            result.stderr,
223            result.exit_code,
224        ))?),
225        Err(Error::SandboxAbort(abort)) => {
226            let partial = PythonReplOutput::new(abort.stdout.clone(), abort.stderr.clone(), 130);
227            let detail = serde_json::to_string(&partial)?;
228            Err(Error::from(abort.with_detail(&detail)).into())
229        }
230        Err(Error::SandboxTimeout(timeout)) => Err(PythonReplTimeoutError::new(timeout)?.into()),
231        Err(error) => Err(ToolError::new(PythonReplError::new(error.to_string()))),
232    }
233}
234
235#[cfg(test)]
236mod tests;