The platform for continuously improving AI agents.
import base64
import http.client
import json
import os
import threading
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from types import SimpleNamespace
from urllib.parse import urlparse
import modal
from celery import current_task
class ProcessProvider:
def __init__(self, network):
self.network = network
self.lock = threading.Lock()
self.accepted = threading.Event()
self.release = threading.Event()
self.effects, self.lookups, self.cancellations = [], [], []
self.tasks = []
self.sandboxes, self.files = {}, {}
self.hidden = set()
self.hold_creation = True
def operation(self, envelope):
operation, values = envelope["operation"], envelope["values"]
held = False
with self.lock:
if operation == "task.event":
self.tasks.append({**values, "pid": envelope["pid"]})
result = None
elif operation == "function.info":
result = {"image_info": {"image_id": "im-process-fixture"}}
elif operation == "volume.create":
result = values["name"]
elif operation == "volume.upload":
self.files[(values["volume"], values["path"].lstrip("/"))] = base64.b64decode(
values["data"]
)
result = None
elif operation == "volume.read":
data = self.files[(values["volume"], values["path"].lstrip("/"))]
result = base64.b64encode(data).decode()
elif operation == "sandbox.create":
identifier = f"sb-process-{len(self.effects) + 1}"
effect = {
"provider_id": identifier,
"pid": envelope["pid"],
"task": envelope["task"],
**values,
}
self.effects.append(effect)
self.sandboxes[identifier] = {**effect, "exit_code": None}
result, held = identifier, self.hold_creation
self.accepted.set()
elif operation == "sandbox.find":
self.lookups.append(values)
result = next(
(
identifier
for identifier, item in self.sandboxes.items()
if identifier not in self.hidden
and item["exit_code"] is None
and all(item[key] == values[key] for key in ("app", "environment", "name"))
),
None,
)
if result is None:
raise KeyError(values["name"])
elif operation == "sandbox.poll":
result = self.sandboxes[values["id"]]["exit_code"]
elif operation == "sandbox.terminate":
self.sandboxes[values["id"]]["exit_code"] = -15
self.cancellations.append(values["id"])
result = None
elif operation == "sandbox.get":
if values["id"] not in self.sandboxes:
raise KeyError(values["id"])
result = values["id"]
elif operation == "billing.rates":
result = {
"gpu_hour_cost_h100": 3.95,
"gpu_hour_cost_h200": 4.54,
"cpu_hour_cost": 0.0473,
"mem_gib_hour_cost": 0.008,
"cpu_hour_cost_sandbox": 0.1419,
"mem_gib_hour_cost_sandbox": 0.024,
}
else:
raise AssertionError(f"Unimplemented provider operation: {operation}")
if held and not self.release.wait(120):
raise TimeoutError("The test did not release the provider response")
return result
@contextmanager
def serve(self):
provider = self
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
request = json.loads(self.rfile.read(int(self.headers["content-length"])))
try:
if "operation" in request:
response = {"result": provider.operation(request)}
else:
status, headers, body = provider.network._route(
request["method"],
request["url"],
base64.b64decode(request["body"]),
request["headers"],
)
response = {
"status": status,
"headers": headers,
"body": base64.b64encode(body).decode(),
}
except KeyError as error:
response = {"error": "not_found", "detail": str(error)}
except Exception as error:
response = {"error": type(error).__name__, "detail": str(error)}
body = json.dumps(response).encode()
try:
self.send_response(200)
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError):
pass
def log_message(self, *_):
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield f"http://127.0.0.1:{server.server_address[1]}"
finally:
self.release.set()
server.shutdown()
server.server_close()
thread.join(timeout=5)
class RemoteModal:
def __init__(self, url):
self.target = urlparse(url)
assert self.target.hostname in {"127.0.0.1", "localhost", "host.docker.internal"}
def call(self, operation, **values):
request = {
"operation": operation,
"values": values,
"pid": os.getpid(),
"task": current_task.request.id if current_task else None,
}
connection = http.client.HTTPConnection(self.target.hostname, self.target.port, timeout=120)
try:
connection.request(
"POST", "/", json.dumps(request), {"content-type": "application/json"}
)
response = json.loads(connection.getresponse().read())
finally:
connection.close()
if response.get("error") == "not_found":
raise modal.exception.NotFoundError(response["detail"])
if response.get("error"):
raise RuntimeError(response)
return response["result"]
def install(self, monkeypatch):
remote = self
class Volume:
def __init__(self, name, **options):
self.name, self.options = name, options
@staticmethod
def from_name(name, **_):
remote.call("volume.create", name=name)
return Volume(name)
def with_mount_options(self, **options):
return Volume(self.name, **options)
@contextmanager
def batch_upload(self):
yield self
def put_file(self, source, path):
remote.call(
"volume.upload",
volume=self.name,
path=path,
data=base64.b64encode(source.read()).decode(),
)
def read_file(self, path):
yield base64.b64decode(remote.call("volume.read", volume=self.name, path=path))
class Sandbox:
def __init__(self, identifier):
self.object_id = identifier
@staticmethod
def create(*args, **kwargs):
result = remote.call(
"sandbox.create",
args=list(args),
name=kwargs["name"],
app=kwargs["app"].name,
environment=kwargs["app"].environment,
image=kwargs["image"],
volumes={
key: {"name": value.name, **value.options}
for key, value in kwargs["volumes"].items()
},
block_network=kwargs["block_network"],
secrets=kwargs["secrets"],
limits={
key: kwargs[key]
for key in ("cpu", "memory", "timeout", "include_oidc_identity_token")
if key in kwargs
},
)
return Sandbox(result)
@staticmethod
def from_name(app, name, environment_name=""):
return Sandbox(
remote.call("sandbox.find", app=app, name=name, environment=environment_name)
)
@staticmethod
def from_id(identifier):
return Sandbox(remote.call("sandbox.get", id=identifier))
def poll(self):
return remote.call("sandbox.poll", id=self.object_id)
def terminate(self, **_):
remote.call("sandbox.terminate", id=self.object_id)
class Function:
@staticmethod
def from_name(app, name, **options):
def info():
result = remote.call("function.info", app=app, name=name, options=options)
return SimpleNamespace(image_info=SimpleNamespace(**result["image_info"]))
return SimpleNamespace(info=info)
monkeypatch.setattr(modal, "Volume", Volume)
monkeypatch.setattr(modal, "Sandbox", Sandbox)
monkeypatch.setattr(modal, "Function", Function)
monkeypatch.setattr(
modal.App,
"lookup",
lambda name, environment_name="", **_: SimpleNamespace(
name=name, environment=environment_name
),
)
monkeypatch.setattr(modal.Image, "from_id", lambda identifier: identifier)
class Rates:
def __call__(self):
return remote.call("billing.rates")
async def aio(self):
return self()
monkeypatch.setattr(
modal,
"Workspace",
SimpleNamespace(
from_context=lambda: SimpleNamespace(billing=SimpleNamespace(rates=Rates()))
),
)