Skip to content

The platform for continuously improving AI agents.

6.2 KB
Raw Blame
import json

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

from overbae.core.errors import InputValidationError
from overbae.models import ResearchAssignment
from overbae.services import context_graph, execution_mandates, research, research_workspace
from overbae.services.experiment_settings import Investigation


def assignment_for(receipt):
    return ResearchAssignment.objects.filter(
        project=receipt.execution.assignment.project,
        request_key=f"flow-research:{receipt.pk}",
    ).first()


@transaction.atomic
def start(receipt, node):
    parent = receipt.execution.assignment
    execution_mandates.require(parent, "author")
    settings = Investigation.model_validate(node["config"])
    principal = parent.agents.get(parent__isnull=True)
    allocation = research.claim(
        principal,
        f"flow:{receipt.pk}",
        "adaptive_research",
        {"config": node["config"], "inputs": receipt.inputs},
    )
    if allocation.state == "denied":
        raise InputValidationError("The research node no longer has execution authority")
    child = assignment_for(receipt)
    if child is not None:
        receipt.action = allocation
        receipt.state = "waiting"
        receipt.save(update_fields=["action", "state"])
        return child
    seconds = min(settings.max_seconds, int((parent.deadline - timezone.now()).total_seconds()))
    if seconds < 60:
        raise InputValidationError("The run has insufficient time remaining for research")
    roots = [
        f"cell:{item['cell']}" if item.get("cell") else f"research_artifact:{item['artifact']}"
        for item in receipt.inputs.values()
        if item.get("cell") or item.get("artifact")
    ]
    child = research.create(
        parent.project,
        user=parent.created_by,
        request_key=f"flow-research:{receipt.pk}",
        objective=settings.objective,
        task={
            "flow_run": str(parent.pk),
            "node": receipt.node,
            "inputs": receipt.inputs,
            "output_contract": dict.fromkeys(
                settings.outputs,
                "Return exactly one independently verified retained artifact in finish.deliverables with this name. Include its ID in finish.artifacts.",
            ),
        },
        acceptance=settings.acceptance,
        context_roots=roots or parent.specification["context_roots"],
        execution_mandate=parent.execution_mandate,
        constraints={**parent.specification["constraints"], "local_platform_data_only": True},
        budget={
            "max_seconds": seconds,
            "max_model_calls": settings.max_model_calls,
        },
    )
    allocation.result = {"assignment": str(child.pk)}
    allocation.state = "running"
    allocation.save(update_fields=["result", "state"])
    receipt.action = allocation
    receipt.state = "waiting"
    receipt.save(update_fields=["action", "state"])
    return child


def advance(receipt, node):
    # Research reconciliation imports the flow executor for stop propagation.
    from overbae.services.research_agent import provider_recovery_pending

    child = assignment_for(receipt)
    if child is None:
        child = start(receipt, node)
    if child.state not in research.TERMINAL or provider_recovery_pending(child):
        return {"state": "waiting", "outputs": {}}
    allocation = receipt.action
    costs = research.recorded_costs(child)
    result = {"assignment": str(child.pk), "state": child.state, "costs": costs}
    # The allocation remains reserved until every child cost is known. Partial
    # provider ledger entries are evidence, not an all-in bill.
    research.complete(allocation, result, cost=costs["all_in_actual_usd"])
    if child.state != "completed":
        return {
            "state": "failed",
            "outputs": {},
            "error": child.result.get("summary") or f"Research {child.state}",
        }
    settings = Investigation.model_validate(node["config"])
    supplied = {item["name"]: item for item in child.result.get("deliverables", [])}
    outputs = {}
    for port in settings.outputs:
        identifiers = supplied.get(port, {}).get("artifacts", [])
        if len(identifiers) != 1 or str(identifiers[0]) not in child.result.get("artifacts", []):
            raise InputValidationError(
                f"Research did not return the exact retained {port} deliverable"
            )
        artifact = child.artifacts.get(pk=identifiers[0])
        kinds = {
            "data": {"data"},
            "model": {"model"},
            "scores": {"evaluation", "benchmark"},
        }
        if artifact.kind not in kinds[port]:
            raise InputValidationError(f"Research returned an incompatible {port} artifact")
        output = {
            "kind": port,
            "artifact": str(artifact.pk),
            "fingerprint": artifact.sha256,
            "path": f"{research_workspace.ROOT}/inputs/artifacts/{artifact.pk}.bin",
            "verification": "independent_research_review",
        }
        if port == "scores":
            report = json.loads(research.artifact_bytes(artifact, limit=2_000_000))
            if not isinstance(report, dict):
                raise InputValidationError("Research scores must be a structured report")
            output["report"] = report
        outputs[port] = output
    receipt.action.experiment_outputs = outputs
    receipt.action.save(update_fields=["experiment_outputs"])
    research.event(
        receipt.execution.assignment,
        "research_handoff",
        {
            "node": receipt.node,
            "assignment": str(child.pk),
            "fingerprint": context_graph.fingerprint(outputs),
            "artifacts": [item["artifact"] for item in outputs.values()],
        },
    )
    return {"state": "completed", "outputs": outputs}


def stop_children(assignment):
    if not hasattr(assignment, "execution"):
        return True
    stopped = True
    for receipt in assignment.execution.nodes.filter(action__tool="adaptive_research"):
        child = assignment_for(receipt)
        if child and (
            child.state not in research.TERMINAL
            or child.state == "blocked"
            and child.result.get("reason") in research.PROVIDER_BLOCKS
        ):
            research.stop(child)
            stopped = False
    return stopped