Skip to content

The platform for continuously improving AI agents.

8.6 KB
Raw Blame
import json
import re

import pytest

from .conftest import GOOD_REPLY, answer_turn
from .datasets import tickets, training_rows, until, upload
from .stack import drain

pytestmark = pytest.mark.covers("train")

PREPARE = "overbae.tasks.training_preparation.reconcile"
TRAIN = "overbae.tasks.finetuning_reconciler.reconcile_finetuning_jobs"
DEPLOY = "overbae.tasks.inference_controller.reconcile_deployments"
BAD_REPLY = "Your refund is on its way. The order was delivered."


def trained_turn(request):
    reply = answer_turn(request)
    if reply.get("tool_calls"):
        return reply
    return {"content": GOOD_REPLY}


def test_train(
    workshop,
    cli,
    sample_agent,
    worker,
    sft,
    serving,
    fake_modal,
    beat,
    fake_llm,
    live_api,
    tmp_path,
    rest_for,
    console,
):
    def served(prefix):
        return lambda r: "inference.test" in r.url and r.model.startswith(prefix)

    fake_llm.extra_models.append("qwen/qwen3.5-9b")
    fake_llm.on(lambda r: r.model == "qwen/qwen3.5-9b", BAD_REPLY)
    fake_llm.on(served("ft-"), trained_turn)
    fake_llm.on("You triage customer support tickets.", "refund")
    answer = workshop.capability("answer")
    path = training_rows(tmp_path)
    correct_rows = [json.loads(line) for line in path.read_text().splitlines()]
    broken_rows = json.loads(json.dumps(correct_rows))
    broken_rows[0]["messages"][-1]["content"] = ""
    path.write_text("".join(json.dumps(row) + "\n" for row in broken_rows))
    train = upload(cli, sample_agent, path, "--intent", "train", "--capability", answer["id"])
    drain(worker)
    project = workshop.project()["id"]
    console.goto(f"/training?projectId={project}&train=true&datasetId={train}")
    console.sees("Dataset needs attention before training")
    assert (
        console._browser.call(
            lambda: console._page.get_by_role("button", name="Copy prompt", exact=True).count()
        )
        == 0
    )
    console.save_evidence("training-dataset-warning")
    console.sees("Example 1, message 3 (assistant):", exact=False)
    console.save_evidence("training-dataset-warning-details")
    source = workshop.call("inspect_dataset", {"dataset": train})["active"]
    repaired = workshop.call(
        "import_dataset_version",
        {
            "dataset": train,
            "source_cell": source["id"],
            "source_fingerprint": source["fingerprint"],
            "name": "Repaired training rows",
            "request_key": "repair-empty-assistant-message",
            "provenance": "Restore the missing assistant answer from the original authored fixture.",
            "imported_rows": [{"source_row": i, **row} for i, row in enumerate(correct_rows)],
        },
    )
    drain(worker)
    assert (
        workshop.call("get_job", {"kind": "dataset_pipeline", "id": repaired["job"]["id"]})[
            "status"
        ]
        == "completed"
    )
    console.goto(f"/training?projectId={project}&train=true&datasetId={train}")
    console.wait_until(
        """() => !document.body.innerText.includes("Dataset needs attention before training") && !document.querySelector('[aria-label="Validating dataset"]')"""
    )
    console._browser.call(
        lambda: (
            console._page.locator("#train-dataset")
            .get_by_text("train.jsonl", exact=True)
            .wait_for()
        )
    )
    console.save_evidence("training-repair-revalidated")
    evals = upload(
        cli, sample_agent, tickets(tmp_path), "--intent", "eval", "--capability", answer["id"]
    )
    drain(worker)

    # An agent authors its own expectation from prose alone, as most agents do.
    expectation = workshop.call(
        "create_eval_matrix_row",
        {
            "name": "resolves-the-ticket",
            "capability": "answer",
            "type": "llm",
            "source": "The reply confirms the delivery and that the refund is on its way.",
        },
    )["row"]["id"]
    eval_set = workshop.call(
        "create_eval_set",
        {"name": "Ticket resolution", "capability": "answer", "rows": [expectation]},
    )["eval_set"]["id"]

    job = workshop.call(
        "start_finetune",
        {
            "request_key": "train-support-model",
            "dataset": train,
            "eval_dataset": evals,
            "eval_set": eval_set,
            "base_model": "Qwen/Qwen3.5-9B",
            "capability": "answer",
        },
    )["finetune"]["id"]
    drain(worker)

    def finetune():
        return workshop.read(f"overmind://finetunes/{job}")

    until(beat, lambda: fake_modal.pending("prepare_"), PREPARE, TRAIN)
    beat(PREPARE, TRAIN)
    assert not fake_modal.called("sft_")

    fake_modal.release("prepare_")
    until(beat, lambda: fake_modal.called("sft_"), PREPARE, TRAIN)
    order = [name for _, name, _, _ in fake_modal.log]
    assert order.index("upload_dataset") < order.index(
        next(n for n in order if n.startswith("sft_"))
    )
    pinned = {c["id"]: c for c in workshop.call("inspect_dataset", {"dataset": train})["cells"]}
    assert pinned[finetune()["cell"]]["frozen"] is True

    fake_modal.release("sft_")

    def benchmarked():
        state = finetune()
        evals = {e["kind"]: e for e in state["progress"].get("judge_evals") or []}
        return state["status"] == "succeeded" and all(
            evals.get(kind, {}).get("status") == "completed" for kind in ("model_before", "final")
        )

    until(beat, benchmarked, PREPARE, TRAIN, DEPLOY)
    state = finetune()
    inventory = workshop.call(
        "list_objects", {"kinds": ["trained_model"], "request_key": "train-support-model"}
    )
    assert [item["id"] for item in inventory["items"]] == [job]
    lineage = workshop.call("inspect_model_lineage", {"training_job": job})
    assert next(cell["id"] for cell in lineage["cells"] if cell["role"] == "train") == state["cell"]
    observed = workshop.call("inspect_jobs", {"jobs": [{"kind": "finetune", "id": job}]})
    assert observed["jobs"][0]["job"]["status"] == "succeeded"
    assert observed["jobs"][0]["job"]["omitted_fields"] == ["progress", "details"]
    assert [p["train_loss"] for p in state["loss"]] == [1.0, 0.5]
    evals = {e["kind"]: e for e in state["progress"]["judge_evals"]}
    assert evals["final"]["aggregate_score"] > evals["model_before"]["aggregate_score"]
    assert evals["final"]["baseline_delta"] > 0
    matrices = [
        [
            m["name"]
            for m in workshop.read(f"overmind://eval-runs/{evals[kind]['eval_run_id']}")["matrix"]
        ]
        for kind in ("model_before", "final")
    ]
    assert matrices[0] == matrices[1] == ["resolves-the-ticket"]

    deployment = state["deployed_model"]
    workshop.call("set_active_model", {"capability": "answer", "deployment": deployment})
    until(
        beat,
        lambda: (workshop.capability("answer")["active_model"] or {}).get("id") == deployment,
        DEPLOY,
    )
    model_id = workshop.read(f"overmind://deployments/{deployment}")["model_id"]
    assert serving.warmed.count(model_id) >= 2

    prompt = workshop.call("get_model_swap_prompt", {"finetune": job})["prompt"]
    alias = re.search(
        r'Set the model parameter of the capability\'s LLM calls to "([^"]+)"', prompt
    )[1]
    base_url = re.search(r"Overmind inference base URL: (\S+)", prompt)[1]
    agent = sample_agent.repo / "support_desk" / "agent.py"
    source = agent.read_text()
    # One OpenAI base URL serves the process, so triage uses the deployed alias.
    agent.write_text(source.replace("model=MODEL", f'model="{alias}"'))

    replies = sample_agent.run(
        "Refund order 42 please",
        api_url=live_api.url,
        llm_url=base_url,
        llm_key=cli.project_key(sample_agent),
    )
    assert replies[-1] == GOOD_REPLY
    metrics = workshop.read(f"overmind://deployments/{deployment}")["metrics"]
    assert metrics["request_count"] >= 2

    rest = rest_for(cli.project_key(sample_agent))
    pinned = rest.request(
        "GET", f"/api/finetuning-jobs/{job}/model-swap-prompt/", params={"pin": "true"}
    )
    assert model_id in pinned["prompt"]
    project = workshop.project()["id"]
    group = rest.request("GET", f"/api/finetuning-jobs/{job}/")["group_id"]
    console._browser.call(
        console._page.context.grant_permissions, ["clipboard-read", "clipboard-write"]
    )
    console.goto(f"/training?projectId={project}&groupId={group}&jobId={job}")
    console.sees("Live model")
    console._browser.call(
        lambda: console._page.get_by_role(
            "button", name=re.compile("^Copy a prompt switching to ")
        ).click()
    )
    console.sees("Prompt copied")
    copied = console._browser.call(console._page.evaluate, "navigator.clipboard.readText()")
    assert alias in copied