Skip to content

The platform for continuously improving AI agents.

13.9 KB
Raw Blame
from collections import defaultdict

from django.conf import settings
from django.db import transaction
from django.db.models import F, Q

from overbae.core.errors import InputValidationError
from overbae.core.model_registry import PROVIDERS, openrouter_configured
from overbae.innermind import runs
from overbae.models import Cell, DeployedModel, EvalRun, EvalSet, FinetuningJob, ModelRef
from overbae.services import (
    context_graph,
    experiment_assets,
    model_catalog,
    research_evidence,
)
from overbae.services.datasets import use
from overbae.services.datasets.contract import public_intent, stored_intents


def check_data(cell, *, freeze=False):
    dataset = cell.dataset
    evaluation_partition = (
        public_intent(dataset.intent) == "train"
        and cell.partition_memberships.filter(
            Q(plan__source_cell__dataset__intent__in=stored_intents("eval"))
            | Q(
                plan__source_cell__intent_report__eval__ok=True,
                plan__source_cell__intent_report__train__ok=False,
            ),
            role="development",
            plan__state="completed",
            plan__project_id=dataset.project_id,
            plan__source_cell__dataset__project_id=dataset.project_id,
            plan__source_cell__fingerprint=F("plan__source_fingerprint"),
        ).exists()
    )
    if evaluation_partition:
        cell = use.check_content(dataset, "eval", cell=cell)
        if freeze:
            use.freeze(cell)
        return cell
    if freeze:
        return use.use(dataset, "eval", cell=cell)
    return use.check(dataset, "eval", cell=cell)


def criteria(project, request):
    if request.suite:
        suite = experiment_assets.get(project, request.suite, "suite")
        definition = suite.definition
        if definition["runtime"] != experiment_assets.scoring_identity():
            raise InputValidationError("The pinned eval set scoring implementation is unavailable")
        return (
            None,
            definition["matrix"],
            {
                "judge_model": definition["judge_model"],
                "judges": {
                    "decision_model": definition["decision_model"],
                    "explanation_models": definition["explanation_models"],
                },
            },
        )
    selected = EvalSet.objects.filter(project=project, pk=request.eval_set).first()
    if selected is None:
        raise InputValidationError("Select an eval set from this project")
    return selected, runs.freeze_matrix(eval_set=selected), {}


def prepare(project, request):
    eval_set, matrix, fields = criteria(project, request)
    if not matrix:
        raise InputValidationError("The selected eval set has no enabled criteria")
    external = {
        candidate.model for candidate in request.participants if candidate.kind == "external"
    }
    if external:
        if not openrouter_configured():
            raise InputValidationError("OpenRouter is unavailable on this deployment")
        catalogue, available = model_catalog.fetch_model_catalog()
        if not available or not external <= {entry["id"] for entry in catalogue}:
            raise InputValidationError("Select exact model IDs from the OpenRouter catalogue")
    return eval_set, matrix, fields


def records(assignment, *, observe=False):
    owners = [str(assignment.pk)]
    if observe:
        owners.extend(
            str(key) for key in research_evidence.flows(assignment).values_list("pk", flat=True)
        )
    return EvalRun.objects.filter(
        project_id=assignment.project_id, params__benchmark_assignment__in=owners
    )


def active(assignment):
    return records(assignment).exclude(status__in=EvalRun.TERMINAL)


def cancel(assignment, *, group=None):
    owned = active(assignment)
    for run in owned.filter(group=group) if group else owned:
        runs.cancel(run)


def target(project, participant):
    if participant.kind == "external":
        provider = PROVIDERS["openrouter"]
        return {
            "model_name": participant.model,
            "model_ref": model_ref(
                project,
                participant,
                model_id=participant.model,
                base_url=provider.base_url,
                key_env=provider.key_env,
            ),
        }
    checkpoint = research_evidence.published_model(project, participant.job)
    if checkpoint is None:
        raise InputValidationError("Select a verified trained checkpoint in this project")
    deployment = (
        DeployedModel.objects.filter(
            project=project,
            finetuning_job_id=participant.job,
            status=DeployedModel.Status.READY,
            inference_contract="chat",
        )
        .exclude(inference_url="")
        .first()
    )
    gateway = (settings.INFERENCE_API_URL or "").rstrip("/")
    if deployment is None or not gateway:
        raise InputValidationError(
            f"{participant.name} needs a ready chat deployment for this eval set"
        )
    return {
        "model_ref": model_ref(
            project,
            participant,
            model_id=deployment.model_id,
            base_url=f"{gateway}/v1",
            key_env="INFERENCE_API_KEY",
        )
    }


def model_ref(project, participant, *, model_id, base_url, key_env):
    ref, _ = ModelRef.objects.get_or_create(
        project=project,
        provider=ModelRef.Provider.CUSTOM,
        model_id=model_id,
        base_url=base_url,
        api_key_ref=key_env,
        finetuning_job_id=participant.job,
        defaults={"label": participant.name},
    )
    return ref


def candidate_id(candidate):
    participant = candidate["participant"]
    return context_graph.fingerprint(
        {
            "kind": participant["kind"],
            "model": participant.get("model") if participant["kind"] == "external" else None,
            "checkpoint": candidate["checkpoint"],
            "instructions": participant["instructions"],
        }
    )


def protocol(cell, request, matrix, fields, selected):
    return {
        "eval_set": str(request.eval_set or request.suite),
        "matrix": matrix,
        "baseline": next(
            candidate_id(candidate)
            for candidate in selected
            if candidate["participant"]["key"] == request.baseline
        ),
        "judge": fields.get("judge_model", ""),
        "judges": fields.get("judges", {}),
        "runtime": experiment_assets.scoring_identity(),
        "capability": str(cell.dataset.capability_id or ""),
    }


def candidates(project, request):
    items = []
    for participant in request.participants:
        definition = participant.model_dump(mode="json", exclude_none=True)
        checkpoint = (
            research_evidence.published_model(project, participant.job) if participant.job else None
        )
        if participant.job and checkpoint is None:
            raise InputValidationError("Select a verified trained checkpoint in this project")
        items.append(
            {
                "participant": definition,
                "checkpoint": checkpoint["fingerprint"] if checkpoint else None,
            }
        )
    return items


def qualification_descriptor(assignment, request):
    cell = (
        Cell.objects.select_related("dataset")
        .filter(pk=request.cell, dataset__project=assignment.project, state="ok")
        .first()
    )
    if cell is None:
        raise InputValidationError("The pinned final input is unavailable")
    _, matrix, fields = criteria(assignment.project, request)
    selected = candidates(assignment.project, request)
    pinned = protocol(cell, request, matrix, fields, selected)
    comparable = (
        EvalRun.objects.filter(
            project=assignment.project,
            params__benchmark_assignment__in=[
                str(key) for key in research_evidence.investigation(assignment)
            ],
            params__benchmark_phase="development",
            status=EvalRun.Status.COMPLETED,
            summary__trust__trusted=True,
        )
        .exclude(cell=cell)
        .select_related("cell")
    )
    evidence = []
    development_cells = {}
    for candidate in selected:
        proof = (
            comparable.filter(params__benchmark_candidate=candidate_id(candidate))
            .order_by("created_at", "pk")
            .first()
        )
        if proof is None:
            raise InputValidationError(
                "Every final candidate needs a complete retained development run"
            )
        development_cells[proof.cell_id] = proof.cell
        evidence.append(
            {
                "evaluation": str(proof.pk),
                "sample_manifest": proof.cell.fingerprint,
                "fingerprint": context_graph.fingerprint(
                    [proof.matrix, proof.params, proof.summary]
                ),
            }
        )
    for development_cell in development_cells.values():
        use.check_held_out(development_cell, cell)
    return {
        "candidates": selected,
        "sealed": [{"cell": str(cell.pk), "fingerprint": cell.fingerprint}],
        "protocol": pinned,
        "development": evidence,
    }


@transaction.atomic
def start(action, request, cell):
    assignment = action.agent.assignment
    existing = list(records(assignment).filter(group=action.pk))
    if existing:
        return describe(existing)
    if request.phase == "development" and (
        action.experiment_inputs.get("data", {}).get("sealed")
        or cell.partition_memberships.filter(role="final").exists()
    ):
        raise InputValidationError("Development benchmarks require an unsealed evaluation dataset")
    eval_set, matrix, fields = prepare(assignment.project, request)
    selected = candidates(assignment.project, request)
    protocol_id = context_graph.fingerprint(protocol(cell, request, matrix, fields, selected))
    if request.phase == "final":
        for job in FinetuningJob.objects.filter(
            project=assignment.project,
            pk__in=[participant.job for participant in request.participants if participant.job],
        ).select_related("cell"):
            if job.cell is not None:
                use.check_held_out(job.cell, cell)
    cell = check_data(cell, freeze=True)
    cohort = []
    for participant, candidate in zip(request.participants, selected, strict=True):
        try:
            run = runs.create_run(
                project=assignment.project,
                cell=cell,
                mode=EvalRun.Mode.GENERATE,
                matrix=matrix,
                name=f"{request.name} · {participant.name}"[:255],
                eval_set=eval_set,
                group=action.pk,
                is_baseline=participant.key == request.baseline,
                triggered_by=assignment.created_by,
                params={
                    "label": participant.name,
                    "benchmark_assignment": str(assignment.pk),
                    "benchmark_participant": participant.model_dump(mode="json", exclude_none=True),
                    "benchmark_eval_set": str(request.eval_set or request.suite),
                    "benchmark_phase": request.phase,
                    "benchmark_protocol": protocol_id,
                    "benchmark_candidate": candidate_id(candidate),
                    **(
                        {"system_prompt": participant.instructions}
                        if participant.instructions
                        else {}
                    ),
                },
                **fields,
                **target(assignment.project, participant),
            )
        except runs.RunError as exc:
            raise InputValidationError(str(exc)) from exc
        runs.launch(run)
        cohort.append(run)
    return describe(cohort)


def describe(cohort):
    first = cohort[0]
    statuses = {run.status for run in cohort}
    state = (
        "running"
        if statuses - set(EvalRun.TERMINAL)
        else "completed"
        if statuses == {"completed"}
        else "cancelled"
        if statuses == {"cancelled"}
        else "failed"
    )
    return {
        "id": str(first.group),
        "state": state,
        "eval_set": first.params["benchmark_eval_set"],
        "cell": str(first.cell_id),
        "phase": first.params["benchmark_phase"],
        "runs": [
            {
                "id": str(run.pk),
                "participant": run.params["benchmark_participant"],
                "state": run.status,
                "report": run.summary,
                "error": run.error,
                "baseline": run.is_baseline,
            }
            for run in cohort
        ],
    }


def observations(assignment):
    cohorts = defaultdict(list)
    for run in records(assignment, observe=True):
        cohorts[run.group].append(run)
    return [describe(cohort) for cohort in cohorts.values()]


def observe(assignment, group):
    cohort = list(records(assignment).filter(group=group).select_related("cell"))
    if not cohort:
        return {"state": "unverified", "outputs": {}}
    record = describe(cohort)
    binding = {
        "kind": "scores",
        "data": record["cell"],
        "phase": record["phase"],
        "eval_set": record["eval_set"],
        "comparison_group": record["id"],
        "evaluation": record["runs"][0]["id"],
        "protocol": cohort[0].params["benchmark_protocol"],
        "sample_manifest": cohort[0].cell.fingerprint,
    }
    binding["reports"] = [
        {
            **binding,
            "evaluation": row["id"],
            "participant": row["participant"],
            "report": {
                **row["report"],
                "completion": {
                    "status": "complete"
                    if row["report"].get("trust", {}).get("trusted")
                    else "incomplete"
                },
            },
            "baseline": row["baseline"],
        }
        for row in record["runs"]
    ]
    return {
        "state": record["state"],
        "error": next((row["error"] for row in record["runs"] if row["error"]), ""),
        "outputs": {"scores": binding} if record["state"] == "completed" else {},
    }