diff --git a/tests/test_automatico.py b/tests/test_automatico.py new file mode 100644 index 0000000..7647428 --- /dev/null +++ b/tests/test_automatico.py @@ -0,0 +1,64 @@ +"""Automático through the API, as the Conectar button uses it: an operator connects +ISSSTELEON's test source and nothing else; the site's language model (LLM_URL: at +ISSSTELEON, its SGLang) drafts the whole pipeline, which is saved and run. What it places +must agree with the pipeline an operator drew, record by record. Real processes and the +real endpoint; nothing faked.""" + +import json + +from test_conectar import ok, wait_for + +SOURCE = "resultados" +HOURS = 3600 # with a model answering, it reads every document: an hour or more per run + + +def staged(platform, pipeline: str) -> dict[tuple, object]: + """What a pipeline's targets staged, clean rows only: (study, record, field) -> value.""" + rows = platform.query( + "select study, _record, field, value_text, value_num, value_bool, value_date " + f"from bronze.staged__observation where _pipeline = '{pipeline}'" + ) + return {(s, r, f): next((v for v in vs if v is not None), None) for s, r, f, *vs in rows} + + +def test_automatico_drafts_a_sites_pipeline_and_runs_it(api, platform, site): + model = ok(api.get("/ingest/llm")) + assert model["available"], model["reason"] + + drawn = json.loads(site.drawn) + source = next(n for n in drawn["nodes"] if n["id"] == SOURCE) + # Automático starts from the sources alone: a drawing with more is refused. + ok(api.put("/ingest/pipelines/half", json={"nodes": drawn["nodes"][:2]})) + assert api.post("/ingest/pipelines/half/draft").status_code == 422 + assert api.post("/ingest/pipelines/nowhere/draft").status_code == 404 + + ok(api.put("/ingest/pipelines/auto", json={"nodes": [source]})) + wait_for(api, ok(api.post("/ingest/pipelines/auto/draft"))["run_id"], seconds=3 * HOURS) + saved = ok(api.get("/ingest/pipelines/auto")) + assert saved["version"] == 2 + kinds = [n["kind"] for n in saved["pipeline"]["nodes"]] + assert {"read", "route", "extract", "link", "target"} <= set(kinds) + studies = {n["entity"] for n in saved["pipeline"]["nodes"] if n["kind"] == "target"} + assert {"cervical_cytology", "mammography"} <= studies, studies + # Documents no route claims wait for a reviewer, as with a drawn pipeline. + assert any(n.get("otherwise") for n in saved["pipeline"]["nodes"]) + + # The operator's own drawing over the same source: where both placed a value, the same. + ok(api.put("/ingest/concept-maps/erick_site", json=json.loads(site.concept_map.read_text()))) + ok(api.put("/ingest/pipelines/site", json=drawn)) + wait_for(api, ok(api.post("/ingest/pipelines/site/runs", json={}))["run_id"], 2 * HOURS) + mine, theirs = staged(platform, "auto"), staged(platform, "site") + both = set(mine) & set(theirs) + differ = {k: (mine[k], theirs[k]) for k in both if str(mine[k]) != str(theirs[k])} + assert both and not differ, differ + for study in ("cervical_cytology", "mammography"): + drawn_records = {r for s, r, _ in theirs if s == study} + assert drawn_records <= {r for s, r, _ in mine if s == study}, study + + # Each case review waits on carries the model's reading, and still waits for a person. + link = next(n["id"] for n in saved["pipeline"]["nodes"] if n["kind"] == "link") + persons = ok(api.get("/review/persons", params={"pipeline": "auto", "node": link})) + for entry in persons["to_settle"]: + assert all(c["suggestion"]["reason"] for c in entry["candidates"]) + for entry in persons["torn"]: + assert entry["suggestion"]["reason"] diff --git a/webapi/ingest.py b/webapi/ingest.py index 2c202dd..481bf96 100644 --- a/webapi/ingest.py +++ b/webapi/ingest.py @@ -10,7 +10,7 @@ from pydantic import BaseModel from core import concept_map from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored from core.schema import ENTITIES -from persistance import config_log, nodes +from persistance import config_log, llm, nodes from webapi.runs import dagster router = APIRouter(prefix="/ingest", tags=["ingest"]) @@ -140,6 +140,42 @@ def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None = raise HTTPException(502, detail=str(e)) from e +class LanguageModel(BaseModel): + available: bool + model: str | None + vision: bool # reads page images (scans), not only their OCR text + reason: str | None # why it is not available + + +@router.get("/llm") +def language_model() -> LanguageModel: + """The site's language model (LLM_URL): whether it answers, which, and whether it + reads images. Automático needs it; extract nodes use their patterns without it.""" + return LanguageModel(**llm.status()) + + +@router.post("/pipelines/{pipeline_id}/draft") +def start_draft( + pipeline_id: PipelineId, client: DagsterGraphQLClient = Depends(dagster) +) -> dict[str, str]: + """Automático: starts the `draft` job, which draws the whole pipeline from its saved + sources (the only nodes it may hold), saves it as a new version and runs it; follow it + at /runs/{run_id}.""" + if not config_log.latest_version(pipeline_id): + raise HTTPException(404, detail=f"no pipeline {pipeline_id}") + _, saved = config_log.get(pipeline_id) + if not saved.nodes or any(n.kind != "source" for n in saved.nodes): + raise HTTPException(422, detail="Automático arma la canalización a partir de sus " + "fuentes: guárdela solo con ellas.") # fmt: skip + if not (found := llm.status())["available"]: + raise HTTPException(503, detail=f"El modelo de lenguaje no responde: {found['reason']}") + config = {"ops": {"draft_pipeline": {"config": {"pipeline": pipeline_id}}}} + try: + return {"run_id": client.submit_job_execution("draft", run_config=config)} + except DagsterGraphQLClientError as e: + raise HTTPException(502, detail=str(e)) from e + + @router.get("/pipelines/{pipeline_id}/nodes/{node_id}/rows") def node_rows( pipeline_id: PipelineId,