Skip to content

The platform for continuously improving AI agents.

3.9 KB
Raw Blame
import logging
from datetime import timedelta
from uuid import UUID

from celery import shared_task
from django.db.models import Max
from django.utils import timezone

logger = logging.getLogger(__name__)

# A workspace holds copies of customer data: one its project has not used for this long is
# deleted, files and all. The next cell creates it again and copies in what it reads.
IDLE_WORKSPACE = timedelta(days=7)


@shared_task(name="overbae.tasks.assistant.run_turn")
def run_turn(thread_id):
    # Lazy: the turn reaches the MCP catalog, which imports the serializers that import tasks.
    from overbae.services.assistant import turn

    turn.run(thread_id)


@shared_task(name="overbae.tasks.assistant.resume_lost_turns")
def resume_lost_turns():
    from overbae.services.assistant import turn

    return {"resumed": turn.resume_lost()}


@shared_task(name="overbae.tasks.assistant.stop_kernel")
def stop_kernel(project_id, thread_id, turn):
    """End the kernel of the turn that was stopped, also during a cell: that turn gets its
    answer and sees the stop. A later turn's kernel is left alone."""
    from overbae.models import AssistantThread
    from overbae.services import workspaces

    if AssistantThread.objects.filter(pk=thread_id, turn=turn, state="running").exists():
        workspaces.provider().stop(project_id, UUID(thread_id).hex)


@shared_task(
    name="overbae.tasks.assistant.forget_workspace_data",
    autoretry_for=(Exception,),
    retry_backoff=60,
    max_retries=10,
)
def forget_workspace_data(project_id, data, conversations):
    """A deleted dataset's copies leave its project's workspace, also at a hosted provider."""
    from overbae.services import workspaces

    workspaces.provider().forget(project_id, data, conversations)


@shared_task(
    name="overbae.tasks.assistant.remove_workspace",
    autoretry_for=(Exception,),
    retry_backoff=60,
    max_retries=10,
)
def remove_workspace(project_id):
    """A deleted project's workspace goes with it, also at a hosted provider."""
    from overbae.services import workspaces

    workspaces.provider().remove(project_id)


@shared_task(name="overbae.tasks.assistant.bill_workspaces")
def bill_workspaces():
    """Charge each project's owner for the workspace compute the provider has measured."""
    from overbae.services import workspaces

    return {"charged": workspaces.provider().bill()}


@shared_task(name="overbae.tasks.assistant.sweep_idle_workspaces")
def sweep_idle_workspaces():
    from overbae.models import AssistantThread
    from overbae.services import workspaces

    provider = workspaces.provider()
    held = {}
    for project in provider.projects():
        try:
            held[project] = UUID(project)
        except ValueError:
            # Not a project's workspace: nothing uses it.
            held[project] = None
    used = dict(
        AssistantThread.objects.filter(project_id__in=[key for key in held.values() if key])
        .values_list("project_id")
        .annotate(last=Max("updated_at"))
    )
    cutoff = timezone.now() - IDLE_WORKSPACE
    idle = [project for project, key in held.items() if used.get(key, cutoff) <= cutoff]
    removed = 0
    for project in idle:
        # A turn may have started since the read above: it keeps the workspace. One that
        # starts during the removal itself loses what it wrote in those seconds; a lock that
        # every cell holds against the removal would close that.
        if (
            held[project]
            and AssistantThread.objects.filter(
                project_id=held[project], updated_at__gt=timezone.now() - IDLE_WORKSPACE
            ).exists()
        ):
            continue
        try:
            provider.remove(project)
        except workspaces.WorkspaceUnavailableError as exc:
            logger.warning("idle workspace %s is not removed yet: %s", project, exc)
            continue
        removed += 1
    return {"removed": removed}