Skip to content

The platform for continuously improving AI agents.

3.7 KB
Raw Blame
import logging

from celery import shared_task
from temporalio.service import RPCError

from overbae.models import ExperimentExecution, ResearchAgent, ResearchAssignment

logger = logging.getLogger(__name__)


@shared_task(acks_late=True, time_limit=1320, soft_time_limit=1300)
def predict_row(attempt_id):
    from overbae.services import experiment_predictions

    experiment_predictions.execute(attempt_id)


@shared_task(acks_late=True, time_limit=1320, soft_time_limit=1300)
def execute_component(execution_id):
    from overbae.services import component_execution

    component_execution.execute(execution_id)


@shared_task(acks_late=True, autoretry_for=(RPCError, OSError), retry_backoff=True, max_retries=5)
def advance(agent_id, wake=True):
    from overbae.services import research_orchestration

    # A wake reaches the agent's workflow at once. Without one, a workflow that is already
    # running is left asleep and only a missing one is started.
    (research_orchestration.nudge if wake else research_orchestration.ensure)(agent_id)


@shared_task(acks_late=True, time_limit=240, soft_time_limit=220)
def advance_flow(execution_id):
    from overbae.services import experiment_engine

    experiment_engine.advance(execution_id)


@shared_task
def settle_stop(assignment_id, attempt=0):
    from overbae.services import research_agent

    # A provider may take a moment to confirm a cancellation; the periodic pass takes over
    # from a run that outlasts these attempts.
    if not research_agent.settle_stop(assignment_id) and attempt < 40:
        settle_stop.apply_async((assignment_id, attempt + 1), countdown=min(5, 0.5 + attempt / 4))


@shared_task
def fire_triggers():
    from overbae.services import research_triggers

    experiments = research_triggers.configured_experiments()
    matched = research_triggers.match_events(experiments=experiments)
    considered = research_triggers.reconcile(experiments=experiments)
    if (
        matched >= research_triggers.PAGE
        or considered >= research_triggers.PAGE
        or research_triggers.pending_due(experiments=experiments)
    ):
        fire_triggers.delay()


@shared_task
def dispatch_wakes():
    from overbae.services import research_wakes

    research_wakes.deliver()


@shared_task
def reconcile():
    from overbae.services import (
        research_agent,  # Training services import API serializers.
        research_qualification,
        research_wakes,
    )

    research_wakes.deliver()
    for assignment in ResearchAssignment.objects.select_related("project", "created_by").iterator(
        chunk_size=100
    ):
        try:
            research_agent.reconcile(assignment)
        except Exception:
            logger.exception("Research reconciliation failed for assignment %s", assignment.pk)
    for identifier in ExperimentExecution.objects.filter(assignment__state="running").values_list(
        "pk", flat=True
    ):
        advance_flow.delay(str(identifier))
    for agent in (
        ResearchAgent.objects.filter(assignment__state="running", state__in=["ready", "waiting"])
        .select_related("assignment__project", "assignment__created_by")
        .iterator(chunk_size=100)
    ):
        advance.delay(str(agent.pk), wake=research_agent.wake_needed(agent))
    for action in research_qualification.pending_actions().select_related("agent__assignment"):
        research_qualification.reconcile(action)
        action.refresh_from_db()
        if action.state == "pending":
            qualify.delay(str(action.pk))


@shared_task(acks_late=True, time_limit=240, soft_time_limit=220)
def qualify(action_id):
    from overbae.services import research_qualification  # Training services import API serializers.

    research_qualification.execute(action_id)