ExDaytona.CodeInterpreter (ex_daytona v0.3.0)

Copy Markdown View Source

Stateful Python execution inside a sandbox.

Unlike ExDaytona.Sandbox.run_code/3 (fresh interpreter per run), the code interpreter keeps state — variables, imports, definitions — between runs, optionally isolated into named contexts:

{:ok, %{}} = ExDaytona.CodeInterpreter.run(sandbox, "counter = 41")
{:ok, %{stdout: "42\n"}} = ExDaytona.CodeInterpreter.run(sandbox, "counter += 1\nprint(counter)")

# Isolated contexts
{:ok, ctx} = ExDaytona.CodeInterpreter.create_context(sandbox, cwd: "/workspace")
{:ok, _} = ExDaytona.CodeInterpreter.run(sandbox, "x = 1", context: ctx)
:ok = ExDaytona.CodeInterpreter.delete_context(sandbox, ctx)

Execution streams over a websocket: pass :on_stdout / :on_stderr callbacks to observe output in real time; the aggregated result is returned either way as %{stdout, stderr, error} (error is %{name, value, traceback} when the code raised, else nil).

Summary

Functions

Create an isolated interpreter context. Options: :cwd.

Delete an interpreter context (by struct or id). Returns :ok.

List the sandbox's interpreter contexts.

Execute Python code with persistent interpreter state.

Types

execution_error()

@type execution_error() :: %{
  name: String.t(),
  value: String.t(),
  traceback: String.t()
}

result()

@type result() :: %{
  stdout: String.t(),
  stderr: String.t(),
  error: execution_error() | nil
}

Functions

create_context(sandbox, opts \\ [])

@spec create_context(
  ExDaytona.Sandbox.t(),
  keyword()
) ::
  {:ok, ExDaytona.Model.InterpreterContext.t()} | {:error, ExDaytona.Error.t()}

Create an isolated interpreter context. Options: :cwd.

delete_context(sandbox, context)

@spec delete_context(
  ExDaytona.Sandbox.t(),
  ExDaytona.Model.InterpreterContext.t() | String.t()
) ::
  :ok | {:error, ExDaytona.Error.t()}

Delete an interpreter context (by struct or id). Returns :ok.

list_contexts(sandbox)

@spec list_contexts(ExDaytona.Sandbox.t()) ::
  {:ok, [ExDaytona.Model.InterpreterContext.t()]}
  | {:error, ExDaytona.Error.t()}

List the sandbox's interpreter contexts.

run(sandbox, code, opts \\ [])

@spec run(ExDaytona.Sandbox.t(), String.t(), keyword()) ::
  {:ok, result()} | {:error, ExDaytona.Error.t()}

Execute Python code with persistent interpreter state.

Options

  • :context — an ExDaytona.Model.InterpreterContext (or its id) to run in (default: the interpreter's default context)
  • :env — environment variables for this run (map)
  • :timeout — API-side execution timeout in seconds
  • :on_stdout / :on_stderrfun(text) streaming callbacks
  • :on_errorfun(%{name, value, traceback}) callback
  • :receive_timeout — max milliseconds to wait for the run to finish client-side (default 300_000)