Skip to content

The platform for continuously improving AI agents.

6.4 KB
Raw Blame
import json

import httpx
import pytest
from factories import make_project, make_user
from fakes.llm import tool_call
from fakes.research_engine import RELEASE, ResearchEngine
from test_experiment_engine import checkpoint_schema as checkpoint_schema
from test_transform_spec import PASSENGERS, SPEC

from overbae.models import APIToken, DataPartitionPlan, Dataset
from overbae.services import research_orchestration
from overbae.services.datasets import land
from overbae.services.experiment_operator import OBJECTIVE

from .stack import settle

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

FLOW = [
    {
        "id": "prepare",
        "kind": "transform",
        "inputs": {"data": "data_0"},
        "settings": {"spec": SPEC},
    },
    {"id": "split", "kind": "split", "inputs": {"data": "prepare"}},
]


@pytest.fixture
def agent_turns(agent_wakes, settings, live_api):
    """A deployment runs each research agent's turns in its Temporal workflow, which advances
    the agent on a wake and again once its executor exits. Here a wake is recorded, and
    ``run()`` gives each agent those turns, running every executor it starts to its exit."""
    engine = ResearchEngine()
    woken = agent_wakes

    def run():
        for _ in range(20):
            while woken:
                research_orchestration.advance(woken.pop(0))
            exited = engine.run_started()
            if not exited:
                return
            woken.extend(exited)
        raise AssertionError("An agent kept starting executors without waiting")

    with engine.serve() as socket:
        settings.RESEARCH_EXECUTOR = "docker"
        settings.RESEARCH_DOCKER_SOCKET = socket
        settings.RESEARCH_DOCKER_IMAGE = RELEASE
        settings.RESEARCH_DOCKER_NETWORK = "research"
        settings.RESEARCH_CALLBACK_URL = f"{live_api.url}/api/internal/research"
        yield run


def test_a_request_on_home_becomes_a_flow_the_platform_runs(
    rest_for, live_api, worker, fake_llm, agent_turns, checkpoint_schema
):
    user = make_user()
    project = make_project(member=user)
    dataset = Dataset.objects.create(project=project, name="Passengers")
    land.land_rows(dataset, PASSENGERS, user=user)
    dataset.refresh_from_db()
    key, _ = APIToken.create_for_user(user, project=project)
    rest = rest_for(key)

    def agent(request):
        # The relay answers inside the API's event loop, so the script reads the conversation.
        # The experiment's operator supervises the run and waits for its next event; the lead
        # defines the whole flow in one call, then hands the definition back.
        if OBJECTIVE in request.text:
            call = tool_call("wait", {"seconds": 600, "reason": "Nothing to change yet"})
        elif not any(
            call["function"]["name"] == "experiment"
            for message in request.messages
            for call in message.get("tool_calls") or []
        ):
            call = tool_call("experiment", {"operation": "define", "run": True, "flow": FLOW})
        else:
            call = tool_call(
                "finish",
                {
                    "delivery": "definition",
                    "outcome": "completed",
                    "summary": "Defined a flow that prepares the passengers and splits them "
                    "by ticket group.",
                },
            )
        return {"content": None, "tool_calls": [call]}

    fake_llm.on(lambda request: bool(request.body.get("tools")), agent)

    sent = {
        "project": str(project.pk),
        "name": "Survival",
        "objective": "Prepare this data to predict survival",
        "cells": [str(dataset.source.pk)],
        "request_key": "home-send",
    }
    created = rest.request("POST", "/api/research-experiments/", json=sent)
    path = f"/api/research-experiments/{created['id']}/"
    # Send again: the same experiment and the same run.
    assert rest.request("POST", "/api/research-experiments/", json=sent)["id"] == created["id"]

    def answered():
        agent_turns()
        shown = rest.request("GET", path)
        return shown if shown["state"] in {"completed", "unmet", "blocked"} else None

    shown = settle(worker, answered, timeout=90)
    assert shown["state"] == "completed", shown["record"]["runs"]
    (chat,) = shown["record"]["runs"]
    assert chat["metrics"]["model_calls"] == 2
    said = [(message["role"], message["status"]) for message in shown["messages"]]
    assert said[0] == ("user", "delivered") and ("assistant", "completed") in said
    # A request on Home only defines the flow; the person runs it from the canvas.
    assert not DataPartitionPlan.objects.filter(project=project).exists()

    revision = shown["version"]
    review = rest.request("POST", path + "plan/", json={"revision": revision})
    started = rest.request(
        "POST",
        path + "run/",
        json={
            "revision": revision,
            "request_key": "home-run",
            "plan_fingerprint": review["fingerprint"],
        },
    )
    identifier = started["record"]["runs"][0]["id"]

    def ran():
        agent_turns()
        run = next(r for r in rest.request("GET", path)["record"]["runs"] if r["id"] == identifier)
        return run if run["state"] in {"completed", "failed", "exhausted"} else None

    flow = settle(worker, ran, timeout=90)
    assert flow["state"] == "completed", flow["result"]
    assert {node["node"]: node["state"] for node in flow["nodes"] if node["current"]} == {
        "data_0": "completed",
        "prepare": "completed",
        "split": "completed",
    }
    plan = DataPartitionPlan.objects.get(project=project)
    members = {member.role: member.cell.rows for member in plan.members.select_related("cell")}
    assert sum(members.values()) == len(PASSENGERS) and members["final"] > 0
    assert plan.recipe["group_by"] == ["ticket_group"]

    # The chat reports the run with the cells it published.
    shown = rest.request("GET", path)
    report = [m["text"] for m in shown["messages"] if m["role"] == "assistant"][-1]
    for member in plan.members.exclude(role="final"):
        assert f"cell={member.cell_id}" in report
    # The live chat carries the same conversation.
    with httpx.stream(
        "GET", f"{live_api.url}{path}events/", headers={"X-Api-Key": key}, timeout=20
    ) as stream:
        frame = next(line for line in stream.iter_lines() if line.startswith("data: "))
    assert [m["id"] for m in json.loads(frame[6:])["messages"]] == [
        m["id"] for m in shown["messages"]
    ]