Skip to navigation

Run untrusted code

Use a sandbox to run code you did not write, such as code a model produced, and send the result back. Outbound traffic from the sandbox is blocked, the code runs as a non-root user, and the sandbox is deleted afterwards.

Next step: run the script below. It needs a key with the models and sandboxes scopes, a stored google key, and a stored daytona key.

The whole flow

A model is asked a question and given one tool, run_python. It answers with code. The script runs that code in a new sandbox and sends the output back, and the model writes the final answer. The model call goes through the OpenAI SDK, and the sandbox calls use requests.

pip install openai requests
export MEADOW_BASE_URL="https://api.usemeadow.ai"
export MEADOW_API_KEY="mdw_..."
import json
import os
import uuid
import requests
from openai import OpenAI
BASE = os.environ["MEADOW_BASE_URL"]
KEY = os.environ["MEADOW_API_KEY"]
HEADERS = {"Authorization": f"Bearer {KEY}"}
MODEL = "gemini-3.1-flash-lite-preview"
llm = OpenAI(base_url=f"{BASE}/v1", api_key=KEY, max_retries=0)
def run_untrusted(code: str) -> dict:
created = requests.post(
f"{BASE}/v1/sandboxes",
headers={**HEADERS, "Idempotency-Key": str(uuid.uuid4())},
params={"wait": "true", "wait_timeout_seconds": 120},
json={
"image": "python:3.12-slim",
"timeout_seconds": 120,
"resources": {"cpu": 1, "memory_mb": 1024},
"network": {"block_all": True},
"provider": {"only": ["daytona"]},
},
timeout=150,
)
created.raise_for_status()
sandbox = created.json()
try:
if sandbox["status"] != "running":
raise RuntimeError(f"sandbox {sandbox['status']}: {sandbox['attempts']}")
url = f"{BASE}/v1/sandboxes/{sandbox['id']}"
upload = requests.put(
f"{url}/files",
headers={**HEADERS, "Content-Type": "application/octet-stream"},
params={"path": "/job/main.py"},
data=code.encode(),
timeout=60,
)
upload.raise_for_status()
result = requests.post(
f"{url}/exec",
headers=HEADERS,
json={"command": ["python", "/job/main.py"], "cwd": "/tmp", "user": "nobody", "timeout_seconds": 20},
timeout=60,
)
result.raise_for_status()
return result.json()
finally:
requests.delete(f"{BASE}/v1/sandboxes/{sandbox['id']}", headers=HEADERS, timeout=60)
tools = [{
"type": "function",
"function": {
"name": "run_python",
"description": "Run a Python 3.12 script and return its output.",
"parameters": {"type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"]},
},
}]
messages = [{
"role": "user",
"content": "Use run_python to print the sum of the squares of 1 to 50, and to print whether "
"https://example.com answers (urllib, timeout 3, catch errors). Then tell me both results in one sentence.",
}]
# The model may ask for the tool more than once, so loop until it answers in text.
for _ in range(4):
reply = llm.chat.completions.create(model=MODEL, messages=messages, tools=tools, max_tokens=400).choices[0].message
messages.append(reply)
if not reply.tool_calls:
break
for tool_call in reply.tool_calls:
result = run_untrusted(json.loads(tool_call.function.arguments)["code"])
print("exit code", result["exit_code"], "timed out", result["timed_out"])
print(result["stdout"], end="")
messages.append({"role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result)})
print(reply.content)

Output from a run against the hosted beta, which took 10 seconds:

exit code 0 timed out False
Sum: 42925
Reachable: False
The sum of the squares from 1 to 50 is 42,925, and https://example.com was not reachable within the 3-second timeout.

The sandbox was running 2 seconds after the create. The first three lines come from the model’s code, so their wording changes from run to run. The model sometimes asks for the tool a second time, so the script loops until the response is text. An earlier version of this script made one tool round only and printed None in those runs. With the loop, six runs in a row ended with a sentence, and two of them used two tool rounds, each in its own sandbox.

What each setting does

SettingWhy
"network": {"block_all": true}Outbound traffic is blocked. In our checks no blocked host returned data. Network rules lists what we tried, including a DNS query on Daytona that still got an answer.
"user": "nobody" on execThe code does not run as root. The user must exist in the image. nobody exists in python:3.12-slim.
"resources": {"cpu": 1, "memory_mb": 1024}A hard limit on both providers, unless you send provider.options.modal.burst. The providers differ in what passing the memory limit does: Daytona kills the command, and Modal ends the whole sandbox. See Resources.
"timeout_seconds": 20 on execThe command is killed after 20 seconds.
"timeout_seconds": 120 on createThe sandbox ends by itself if your process dies before the delete.
Idempotency-Key on createA retry of the create cannot start a second sandbox.
A new sandbox per job, deleted in finallyOne job cannot read what another left behind.

What bad code does

We ran each of these as nobody in a Daytona sandbox with 1 CPU and 1024 MB. Every call returned 200. Read exit_code and timed_out to see how the command ended.

The codeWhat came back
Allocates memory without endexit_code: 137, timed_out: false, after about 950 MB. The sandbox stayed running.
Loops forever, with timeout_seconds: 3timed_out: true, exit_code: 143, after 3.6 seconds.
Fills the diskThe write stopped at the sandbox’s disk_mb, 3 GiB by default.
Prints 5 MiBThe first 4 MiB, with stdout_truncated: true. See Output caps.
Calls a blocked addressAn error inside the code, such as URLError.

The disk and output rows come from an earlier run on the hosted beta. We reran the others for this page.

Twelve blocking commands sent to one sandbox at the same time all ran, and finished in 3.6 seconds for a 2 second command. Meadow sets no limit on commands per sandbox.

Things to know

  • Exec user needs a tool in the image that can switch users: setpriv, runuser, su, or python3. Debian and Ubuntu images have one. A missing user, or an image with none of these, returns 400.
  • Uploaded files belong to root with mode 0644. nobody can read and run /job/main.py through python, and cannot write next to it. Give the code a writable place: /tmp, or a directory you chown first. See Files, ports, and SSH.
  • Code in the sandbox can read the sandbox’s environment. Put no secret in env that the code should not see. See Security.
  • With block_all, nothing can be installed at run time. Build the packages you need into an image. A sandbox from a built image takes resources like any other.
  • Background commands keep their state in /tmp/.meadow-exec inside the sandbox. Code that removes or takes over that directory breaks later background commands in the same sandbox. With one sandbox per job this does not matter.
  • On Daytona, stderr of a command that could not start begins with the path of Meadow’s wrapper script. Strip it before you send stderr to a model. See Running commands.
  • A sandbox takes about 2 seconds to start on Daytona. To reuse one for several jobs, keep it and run each job with exec. The jobs then share one file system, so do that only for jobs that may see each other’s files.

More in Known limits.

API reference

Operations on this page: createChatCompletion, createSandbox, uploadFile, execInSandbox, deleteSandbox.