Skip to content

The platform for continuously improving AI agents.

4.7 KB
Raw Blame
"""Research executors as Modal Sandboxes. A release is the Modal image built from
docker/research/Dockerfile, named by its image id, so a conversation keeps running on the
image it started with after the source moves on. Two Modal Dicts remember what a Sandbox
cannot tell once it ended: each release's dependency digest, and each launch's Sandbox."""

import hashlib
import os
from functools import cache
from pathlib import Path
from urllib.parse import urlparse

import modal
from django.conf import settings
from modal.exception import AlreadyExistsError

from overbae.services.research_executor.launch import (
    RUNNER,
    ExecutorUnavailableError,
    Launch,
    Status,
    mismatch,
)

APP = "overmind-research"
ROOT = Path(__file__).resolve().parents[3]
DOCKERFILE = ROOT / "docker" / "research" / "Dockerfile"
LOCK = ROOT / "docker" / "research" / "requirements.lock"
SOURCE = ROOT / "agent_runtime"
CPU = 2.0
MEMORY = 2048
# One burst of turns; the workflow's activity ends sooner and the next epoch starts anew.
LIFE_SECONDS = 2 * 60 * 60


def _environment():
    return os.environ["MODAL_ENVIRONMENT"]


@cache
def _app():
    return modal.App.lookup(APP, environment_name=_environment(), create_if_missing=True)


@cache
def _dict(name):
    return modal.Dict.from_name(name, environment_name=_environment(), create_if_missing=True)


def _dependencies_digest():
    return hashlib.sha256(DOCKERFILE.read_bytes() + LOCK.read_bytes()).hexdigest()


@cache
def _release():
    try:
        image = modal.Image.from_dockerfile(DOCKERFILE, context_dir=ROOT).build(_app())
        _dict("overmind-research-releases")[image.object_id] = _dependencies_digest()
    except modal.exception.Error as error:
        raise ExecutorUnavailableError("The research image did not build") from error
    return image.object_id


class ModalExecutor:
    def release(self):
        return _release()

    def dependencies(self, release):
        return _dict("overmind-research-releases").get(release)

    def _sandbox(self, launch):
        identifier = _dict("overmind-research-launches").get(launch.name)
        if identifier is None:
            return None
        sandbox = modal.Sandbox.from_id(identifier)
        tags = sandbox.get_tags()
        if tags.get("release") != launch.release or any(
            tags.get(key) != value for key, value in launch.labels.items()
        ):
            raise mismatch()
        return sandbox

    def launch(self, launch: Launch, environment):
        try:
            if self._sandbox(launch) is not None:
                return
            callback = urlparse(settings.RESEARCH_CALLBACK_URL).hostname
            try:
                sandbox = modal.Sandbox.create(
                    *RUNNER,
                    app=_app(),
                    name=launch.name,
                    tags={**launch.labels, "release": launch.release},
                    image=modal.Image.from_id(launch.release),
                    env=environment,
                    cpu=CPU,
                    memory=MEMORY,
                    timeout=LIFE_SECONDS,
                    workdir="/opt/runtime",
                    # The model is reached through the platform's metered relay, so the platform is
                    # the only host a runner talks to.
                    outbound_domain_allowlist=[callback],
                    volumes={
                        path: modal.Volume.from_name(
                            name,
                            environment_name=_environment(),
                            create_if_missing=True,
                            version=2,
                        )
                        for name, path in launch.volumes.items()
                    },
                )
            except AlreadyExistsError:
                sandbox = modal.Sandbox.from_name(APP, launch.name, environment_name=_environment())
            _dict("overmind-research-launches")[launch.name] = sandbox.object_id
        except modal.exception.Error as error:
            raise ExecutorUnavailableError("The research executor did not start") from error

    def status(self, launch):
        try:
            sandbox = self._sandbox(launch)
            if sandbox is None:
                return None
            code = sandbox.poll()
        except modal.exception.Error as error:
            raise ExecutorUnavailableError("Modal did not answer") from error
        return Status("running") if code is None else Status("exited", code)

    def stop(self, launch):
        try:
            sandbox = self._sandbox(launch)
            if sandbox is not None and sandbox.poll() is None:
                sandbox.terminate(wait=True)
        except modal.exception.Error as error:
            raise ExecutorUnavailableError("Modal did not answer") from error