Skip to content

The platform for continuously improving AI agents.

8.9 KB
Raw Blame
import json

from django.db import transaction
from django.db.models import Q
from django.utils import timezone

from overbae.core.errors import InputValidationError
from overbae.models import ResearchAssignment
from overbae.services import execution_mandates


def flow_bound(assignment):
    """An experiment chat has one lead; an adaptive Research stage has its own evaluator."""
    return bool(assignment.experiment_revision_id) and not hasattr(assignment, "execution")


def current(agent):
    if agent.parent_id or not agent.assignment.experiment_revision_id:
        return None
    return for_assignment(agent.assignment)


def boundary_of(assignment):
    """The event that opened the request in hand. A recovery from a provider outage resumes
    the same request: it carries no instructions and opens nothing."""
    return (
        assignment.events.filter(kind__in=["resumed", "request_received"])
        .exclude(kind="resumed", payload__has_key="automatic")
        .order_by("-pk")
        .first()
    )


def for_assignment(assignment):
    boundary = boundary_of(assignment)
    if boundary is None:
        return None
    text = boundary.payload["instructions"]
    for amendment in amendments(assignment, after=boundary.pk):
        if amendment.get("questions"):
            text += "\n\nQuestion:\n" + json.dumps(amendment["questions"])
        text += "\n\nUser follow-up:\n" + amendment["text"]
    return {"id": boundary.pk, "text": text, "started_at": boundary.created_at}


def amendments(assignment, *, after=0):
    messages = list(
        assignment.events.filter(
            Q(payload__has_key="user_message") | Q(payload__has_key="question"),
            pk__gt=after,
            kind="agent_message",
            payload__sender="user",
        )
        .order_by("pk")
        .values_list("payload", flat=True)
    )
    questions = {
        payload["question"]: payload["questions"]
        for payload in assignment.events.filter(
            kind="user_question",
            payload__question__in=[
                message["question"] for message in messages if "question" in message
            ],
        ).values_list("payload", flat=True)
    }
    return [
        {
            "text": message["message"],
            **(
                {"questions": questions[message["question"]]}
                if message.get("question") in questions
                else {}
            ),
        }
        for message in messages
    ]


def settled(assignment, request):
    """Whether the request has been answered, so the next message opens another."""
    return assignment.events.filter(
        kind="request_completed", payload__request=request["id"]
    ).exists()


def undelivered(assignment):
    """User messages the runtime still owes the lead; a removed one is never owed."""
    return assignment.user_messages.filter(sdk_event_id__isnull=True).exclude(state="removed")


def instruction_history(assignment):
    messages = {
        item["request_key"]: str(item["id"])
        for item in assignment.user_messages.values("request_key", "id")
    }
    events = (
        assignment.events.filter(
            Q(kind__in=["request_received", "resumed", "question_answered"])
            | Q(kind="agent_message", agent__isnull=True, payload__sender="user")
        )
        .exclude(kind="resumed", payload__has_key="automatic")
        .order_by("-pk")
    )
    questions = {
        event["payload"]["question"]: event["payload"]["questions"]
        for event in assignment.events.filter(kind="user_question").values("payload")
    }
    records, size, seen = [], 0, set()
    for event in events[:200]:
        payload = event.payload
        text = payload.get("instructions") or payload.get("message") or payload.get("text")
        if not text:
            continue
        message_id = payload.get("user_message") or (
            payload.get("message") or messages.get(payload.get("request_key"))
            if "instructions" in payload
            else None
        )
        if message_id and message_id in seen:
            continue
        entry = {
            "event": event.pk,
            "at": event.created_at.isoformat(),
            "kind": event.kind,
            "user_message": message_id,
            "question": payload.get("question"),
            "questions": questions.get(payload.get("question")),
            "text": text,
        }
        length = len(json.dumps(entry))
        if size + length > 32000:
            break
        records.append(entry)
        size += length
        if message_id:
            seen.add(message_id)
    return {
        "authority": "User instruction provenance; only the current request defines work to complete.",
        "entries": list(reversed(records)),
        "omitted_events": max(0, events.count() - len(records)),
    }


# Tools that address a teammate. A lead that works alone has none to address.
TEAM_TOOLS = {"delegate", "manage_agent", "review_handoff", "message_agent", "inspect_agent"}
# Experiment operations that save the flow.
AUTHORING = ("stage", "define", "remove")

CANVAS_EXECUTION = "Use Run on the canvas to review and start the saved flow."
RUN_INVITATION = (
    "Would you like to run this flow? "
    f"{CANVAS_EXECUTION} The background agent will monitor the run."
)


def construction_only(assignment):
    return flow_bound(assignment) and boundary_of(assignment) is not None


# Operation families a flow stage states. The workspace and a dataset import have no stage kind,
# and a Workshop delegation publishes the dataset a flow then names as its source.
STAGED = {"prepare", "train", "evaluate", "qualify", "serve"}
UNSTAGED = {"experiment", "workspace", "import_dataset", "workshop"}


def workshop_owned(tool, arguments):
    return tool == "retain_pipeline" or (
        tool == "platform"
        and arguments.get("name")
        in {
            "save_dataset_pipeline",
            "validate_dataset_pipeline",
            "run_dataset_pipeline",
            "prepare_dataset",
            "create_data_partition",
        }
        and not arguments.get("describe")
    )


def permits(agent, tool, arguments):
    if not flow_bound(agent.assignment):
        return True
    return not (agent.parent_id or tool in TEAM_TOOLS or workshop_owned(tool, arguments))


def owed_to_a_stage(action):
    """An experiment lead's own call for work that its flow starts, so the canvas shows it."""
    return (
        flow_bound(action.agent.assignment)
        and action.tool not in UNSTAGED
        and not action.experiment_node
        and not action.request_key.startswith("flow:")
        and execution_mandates.operation_family(action.tool, action.arguments) in STAGED
    )


@transaction.atomic
def finish(action, request, *, record=None):
    """Retain the answer or definition and close its current request."""
    from overbae.services import (  # Native completion shares the research lease.
        research,
        research_experiments,
        research_team,
    )

    agent = action.agent
    assignment = ResearchAssignment.objects.select_for_update().get(pk=agent.assignment_id)
    scope = current(agent)
    queued = assignment.user_messages.filter(state="pending").exists()
    revision = research_experiments.current_revision(assignment)
    result = {
        **request.model_dump(mode="json"),
        "request": scope["id"],
        "revision": revision.number,
        "fingerprint": revision.fingerprint,
    }
    if request.delivery == "answer":
        result |= record or {}
    else:
        receipts = list(
            agent.actions.filter(
                created_at__gte=scope["started_at"],
                tool="experiment",
                arguments__operation__in=AUTHORING,
                state="completed",
            ).order_by("created_at")
        )
        if request.outcome == "completed" and (
            not receipts or receipts[-1].result.get("fingerprint") != revision.fingerprint
        ):
            raise InputValidationError(
                "A definition is delivered once this request has saved the flow. Save the "
                "change with experiment(operation=stage) or experiment(operation=define), "
                "or finish with outcome unmet or blocked and say why."
            )
        result |= {"verified_changes": [receipt.result for receipt in receipts]}
    agent = research_team.transition(
        agent,
        fence=agent.lease,
        state="ready" if queued else request.outcome,
        result=result,
        completed_at=None if queued else timezone.now(),
    )
    assignment.state, assignment.result, assignment.completed_at = (
        "running" if queued else request.outcome,
        result,
        None if queued else timezone.now(),
    )
    assignment.save(update_fields=["state", "result", "completed_at"])
    research.event(
        assignment,
        "request_completed",
        {"request": scope["id"], "revision": revision.number, "outcome": request.outcome},
    )
    return agent.result