Skip to content

dspy.PythonInterpreter

dspy.PythonInterpreter(deno_command: Optional[List[str]] = None)

PythonInterpreter that runs code in a sandboxed environment using Deno and Pyodide.

Prerequisites: - Deno (https://docs.deno.com/runtime/getting_started/installation/).

Example Usage:

code_string = "print('Hello'); 1 + 2"
interp = PythonInterpreter()
output = interp(code_string)
print(output)  # If final statement is non-None, prints the numeric result, else prints captured output
interp.shutdown()

Source code in dspy/primitives/python_interpreter.py
def __init__(
    self,
    deno_command: Optional[List[str]] = None
) -> None:
    if isinstance(deno_command, dict):
        deno_command = None  # no-op, just a guard in case someone passes a dict
    self.deno_command = deno_command or [
        "deno", "run", "--allow-read", self._get_runner_path()
    ]
    self.deno_process = None

Functions

__call__(code: str, variables: Optional[Dict[str, Any]] = None) -> Any

Source code in dspy/primitives/python_interpreter.py
def __call__(
    self,
    code: str,
    variables: Optional[Dict[str, Any]] = None,
) -> Any:
    return self.execute(code, variables)

execute(code: str, variables: Optional[Dict[str, Any]] = None) -> Any

Source code in dspy/primitives/python_interpreter.py
def execute(
    self,
    code: str,
    variables: Optional[Dict[str, Any]] = None,
) -> Any:
    variables = variables or {}
    code = self._inject_variables(code, variables)
    self._ensure_deno_process()

    # Send the code as JSON
    input_data = json.dumps({"code": code})
    try:
        self.deno_process.stdin.write(input_data + "\n")
        self.deno_process.stdin.flush()
    except BrokenPipeError:
        # If the process died, restart and try again once
        self._ensure_deno_process()
        self.deno_process.stdin.write(input_data + "\n")
        self.deno_process.stdin.flush()

    # Read one JSON line from stdout
    output_line = self.deno_process.stdout.readline().strip()
    if not output_line:
        # Possibly the subprocess died or gave no output
        err_output = self.deno_process.stderr.read()
        raise InterpreterError(f"No output from Deno subprocess. Stderr: {err_output}")

    # Parse that line as JSON
    try:
        result = json.loads(output_line)
    except json.JSONDecodeError:
        # If not valid JSON, just return raw text
        result = {"output": output_line}

    # If we have an error, handle SyntaxError vs. other error
    if "error" in result:
        error_msg = result["error"]
        error_type = result.get("errorType", "")
        if error_type == "SyntaxError":
            raise SyntaxError(error_msg)
        else:
            raise InterpreterError(f"Sandbox Error: {error_msg}")

    # If there's no error, return the "output" field
    return result.get("output", None)

shutdown() -> None

Source code in dspy/primitives/python_interpreter.py
def shutdown(self) -> None:
    if self.deno_process and self.deno_process.poll() is None:
        shutdown_message = json.dumps({"shutdown": True}) + "\n"
        self.deno_process.stdin.write(shutdown_message)
        self.deno_process.stdin.flush()
        self.deno_process.stdin.close()
        self.deno_process.wait()
        self.deno_process = None