Skip to content

Code Execution

View as Markdown

Daytona runs Python, TypeScript, and JavaScript code in sandboxes through language kernels, so untrusted or generated code executes in isolation from your application.

Every run is a code process that executes in a session with a language kernel. The kernel keeps state between runs in the same session, so variables, imports, and functions defined in one run are available in the next. Runs use a shared kernel per language by default; isolated runs and interpreter contexts give code its own kernel. To run shell commands and manage long-running processes, see process execution. To follow a run’s output live, see log streaming.

Code execution is used when an application runs Python, TypeScript, or JavaScript that it did not write or does not trust.

  • AI-generated code: an agent writes code, runs it in the sandbox, and reads the output and errors to correct its next attempt. The code runs isolated from your application.
  • Data analysis: the kernel keeps data, imports, and functions in memory between runs, so each step builds on the previous one, as in a notebook.
  • Charts and tables: runs that plot or display data return charts and tables as artifacts with the result. Each artifact is keyed by MIME type, so an application renders it in the right format.
  • Code interpreters for users: each user or conversation gets its own interpreter context, so state from one does not reach another. A context has its own kernel, working directory, and environment.
  • Workers that share a context: contexts are addressed by ID. Any worker or process with the sandbox ID and the context ID runs code in the same context.
  • Live output from long runs: the output of a run streams through log streaming while the code still runs. Exceptions arrive with their name, value, and traceback.
  • One-off runs: an isolated kernel runs code with no state from earlier runs. The session is deleted after the run, so nothing the code defines reaches other runs.

Run code in a sandbox. Runs without a context share one kernel per language, so state from one run is available to later runs in that language. The default language is Python.

The result contains the standard output and standard error, rich outputs, the exception if the code raised one, and the exit status of the process.

from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
response = sandbox.run_code('''
def greet(name):
return f"Hello, {name}!"
print(greet("Daytona"))
''')
print(response.logs.stdout)
ParameterTypeDescription
codestrSets the code to run. This parameter is required.
languagestrSets the language: python, typescript, or javascript. The default is python.
contextInterpreterContextRuns the code in an interpreter context instead of the shared kernel.
isolatedboolRuns the code in a temporary kernel. The default is False.
cwdstrSets the working directory for the run.
envMapping[str, str]Sets environment variables for the shared kernel. The variables apply when the kernel is first created.
timeoutfloatSets how many seconds the client waits. 0 means no limit. On timeout, the kernel is interrupted and the interrupted result is returned.

The response has the following fields:

FieldDescription
logsHolds the standard output and standard error.
resultsHolds the rich outputs.
errorHolds the exception, if the code raised one.
processHolds the exit status of the process.
  • run_code is a shortcut for sandbox.interpreter.run and accepts the same parameters.

Rich outputs such as charts and tables are returned with the result, keyed by MIME type.

from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
code = '''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 30)
plt.plot(x, np.sin(x))
plt.title("Sine wave")
plt.show()
'''
response = sandbox.run_code(code)
for result in response.results:
print(list(result.data)) # MIME types, for example ['image/png', 'text/plain']

The response has the following fields:

FieldDescription
resultsHolds the rich outputs.
text, html, png, svg, jsonEach of these fields of a result mirrors the matching MIME type in data.
is_main_resultIs True for the value of the last expression and False for displayed outputs.

Run code in a temporary kernel that starts with no state. Daytona creates a session with a new kernel, runs the code, and deletes the session after the run. Nothing the code defines is visible to other runs, and the code does not see state from the shared kernel or from interpreter contexts.

from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
sandbox.run_code("value = 42")
# The isolated kernel does not see variables from the shared kernel
response = sandbox.run_code("print(value)", isolated=True)
if response.error:
print(response.error.name) # NameError
ParameterTypeDescription
isolatedboolRuns the code in a temporary kernel when set to True. The default is False.
cwdstrSets the working directory of the temporary kernel.
envMapping[str, str]Sets environment variables of the temporary kernel.

An interpreter context is a session with its own language kernel, working directory, and environment. State persists across runs in a context and is not shared with the shared kernel or other contexts. A context lives until deleted, so its kernel uses memory while idle.

In the Toolbox API, a context is a session whose kernel is a language. Sessions with a shell kernel run shell commands; see sessions.

Create an interpreter context and run code in it. Run code with the context handle, or pass the handle to a run in the sandbox.

from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
ctx = sandbox.interpreter.create_context(language="python", env={"STAGE": "dev"})
try:
ctx.run("value = 'stored in ctx'")
result = sandbox.run_code("print(value)", context=ctx)
print(result.logs.stdout)
finally:
ctx.close()
ParameterTypeDescription
languagestrSets the language: python, typescript, or javascript. This parameter is required.
context_idstrSets the context ID for reconnecting later. If omitted, an ID is generated.
cwdstrSets the working directory of the kernel.
envMapping[str, str]Sets the kernel environment variables. Runs in a context do not accept env.
  • create_context() starts the kernel before it returns.
  • The first context or run in a language also installs the kernel, so the call can take longer than a run.

List a sandbox’s interpreter contexts. The API also lists shell sessions; the SDKs do not.

from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
for ctx in sandbox.interpreter.list_contexts():
print(f"Context: {ctx.context_id}, Language: {ctx.language}")

Reconnect to an existing context from another worker or process. Contexts are addressed by ID, so any client with the sandbox ID and the context ID can run code in the context.

from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
# Worker A: create a context with a known ID
ctx = sandbox.interpreter.create_context(language="python", context_id="my-context")
ctx.run("x = 42")
# Worker B: reconnect to the context by ID
context = sandbox.interpreter.connect_context("my-context", language="python")
response = context.run("print(x)")
ParameterTypeDescription
languagestrSets the context language. This parameter is required when you pass an ID. Without language, connect_context() raises DaytonaError with code BAD_REQUEST.
  • connect_context() returns a handle for the context ID and language without a request or existence check.
  • A run in a deleted context fails.

Delete an interpreter context. Deleting a context shuts its kernel down and frees its memory.

from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
ctx = sandbox.interpreter.create_context(language="python")
try:
ctx.run("data = list(range(10_000_000))")
finally:
sandbox.interpreter.delete_context(ctx)
  • delete_context() takes a handle or ID.
  • ctx.close() deletes the context of a handle.