From 929759d248f8334de5d9af53c1ae42562c016b23 Mon Sep 17 00:00:00 2001 From: Birfy <15378933+Birfy@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:47:07 +0800 Subject: [PATCH] Add Cloudflare Clef / Clef-flash as a served System One backend --model clef talks to Workers AI or a local /v1/systemone server (CLEF_URL, or CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_AUTH_TOKEN; CLEF_MODEL=clef|clef-flash, default clef-flash). Screenshots map to Clef's images array (max 4); a text observation still runs. Contract tests use a stub server; no live Cloudflare or GPU call in CI. --- .env.example | 8 + CHANGELOG.md | 10 + NOTICE | 2 + THIRD_PARTY_LICENSES.md | 8 + docs/agents.md | 6 +- docs/architecture.md | 7 +- docs/capabilities.md | 1 + docs/configuration.md | 6 + docs/decision-models.md | 25 +- s1a/browser/browse.py | 5 +- s1a/cli.py | 7 +- s1a/decision_models/__init__.py | 2 + s1a/decision_models/clef.py | 421 +++++++++++++++++++++++ s1a/decision_models/factory.py | 4 + s1a/mcp_server.py | 8 +- s1a/rails.py | 4 +- s1a/tool/loop.py | 4 +- s1a/tool/series.py | 4 +- tests/test_browse.py | 2 +- tests/test_clef_registration.py | 105 ++++++ tests/test_decision_models_clef.py | 476 ++++++++++++++++++++++++++ tests/test_decision_models_factory.py | 14 +- tests/test_mcp_server.py | 4 +- 23 files changed, 1107 insertions(+), 26 deletions(-) create mode 100644 s1a/decision_models/clef.py create mode 100644 tests/test_clef_registration.py create mode 100644 tests/test_decision_models_clef.py diff --git a/.env.example b/.env.example index 10590f3..7e7291a 100644 --- a/.env.example +++ b/.env.example @@ -68,6 +68,14 @@ MODEL_NAME=google/gemini-2.5-flash # OMNIJEV_BASE=Qwen/Qwen3.5-0.8B # the Qwen3.5 backbone of the same size # OMNIJEV_PROMPT=full # full: text state + goal + rules; short: goal + ask over the screenshot +# ---- Clef / Clef-flash (behind --model clef; Workers AI or a local /v1/systemone server, no extra needed) ---- +# CLEF_URL=http://127.0.0.1:30000 # local SGLang (lmsysorg/sglang:dev-clef); wins over Workers AI when set +# CLOUDFLARE_ACCOUNT_ID= # Workers AI, used only when CLEF_URL is unset +# CLOUDFLARE_AUTH_TOKEN= # official Clef-docs name; CLOUDFLARE_API_TOKEN is accepted as an alias +# CLEF_MODEL=clef-flash # or clef (27B). Default clef-flash (9B) for latency +# CLEF_API_KEY= # when a local server expects a bearer token +# CLEF_TIMEOUT_S=30 # per decision, the one refused-connection / 502 / 504 retry included + # ---- Optional Cua-S1 4B ---- # uv sync --extra cua-four-b (separate from the Laya demo). # CUA_S1_VARIANT=4b diff --git a/CHANGELOG.md b/CHANGELOG.md index 37b99a8..e033d51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); ver ## Unreleased +### Added + +- `--model clef`: [Clef](https://huggingface.co/Cloudflare/clef) / [Clef-flash](https://huggingface.co/Cloudflare/clef-flash) + (Apache-2.0) as a **served** multimodal System One client against Cloudflare Workers AI or a local + `/v1/systemone` server (`CLEF_URL`, or `CLOUDFLARE_ACCOUNT_ID` + `CLOUDFLARE_AUTH_TOKEN`; `CLEF_MODEL=clef|clef-flash`, + default `clef-flash`). Posts choice/noul with Clef's `images` array (PNG/JPEG/WebP data URLs, max 4) when the + observation has screenshots; a text observation still runs. `score` questions and `videos` are unsupported on + our interface (Workers AI Clef / Clef-flash also has no `videos` field). Contract tests use a fake HTTP server; + live Workers AI / GPU qualification is not claimed (#126). + ## 0.4.0 - 2026-11-13 ### Added diff --git a/NOTICE b/NOTICE index d66d358..9b8bee7 100644 --- a/NOTICE +++ b/NOTICE @@ -23,3 +23,5 @@ This product includes software developed by third parties: Beurer-Kellner, Marc Fischer, and Florian Tramèr). Full license text: THIRD_PARTY_LICENSES.md - s1a/decision_models/onejev.py: HTTP client for OneJev / qev (OmniJev/OneJev), Apache-2.0; the weights and server are not vendored. Details: THIRD_PARTY_LICENSES.md +- s1a/decision_models/clef.py: HTTP client for Cloudflare Clef / Clef-flash, Apache-2.0; + the weights and serving image are not vendored. Details: THIRD_PARTY_LICENSES.md diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index ac25900..9d1db4a 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -126,3 +126,11 @@ OneJev and its serving code are Apache License 2.0 (Copyright OmniJev Team). Thi vendor OneJev weights, training code, or the `qev`/`flide` packages; install and run them separately per the model card. The unrelated PyPI package named `qev` is not the OneJev server — install from the OneJev GitHub repository as the model card instructs. + +The `--model clef` adapter (`s1a/decision_models/clef.py`) talks to Cloudflare Clef or Clef-flash +through Workers AI or a local SGLang `/v1/systemone` server. Clef / Clef-flash weights and the +model card are Apache License 2.0 (Copyright Cloudflare). This repository does not vendor the +weights, `joint_schema_model.py`, or the `lmsysorg/sglang:dev-clef` serving image; use Workers AI +or install and run them separately per +https://huggingface.co/Cloudflare/clef and +https://developers.cloudflare.com/workers-ai/models/clef/. diff --git a/docs/agents.md b/docs/agents.md index 087cf1a..934613e 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -17,12 +17,12 @@ hook of a running agent. The injection guard rail fails closed: a decision error | `blackjack` | tool | payoff per hand (RLCard) | `s1a run blackjack --model jev --rethink off --episodes 100` | | `injection_guard` | rail | precision and recall on a labelled injection set | `s1a run injection_guard` | -Every tool agent takes `--model jev|clm|laya|laya-served|cua|llm|random|rule`, `--rethink on|off`, `--episodes N`, `--seed S`, +Every tool agent takes `--model jev|clm|laya|laya-served|cua|clef|llm|random|rule`, `--rethink on|off`, `--episodes N`, `--seed S`, `--max-steps` and `--timeout`, and writes a Harbor-shaped job folder under `evals/results//`. A browser agent -takes `--model jev|clm|laya|laya-served|cua|omnijev|onejev|llm`, `--goal` and the same `--rethink` flag. +takes `--model jev|clm|laya|laya-served|cua|omnijev|onejev|clef|llm`, `--goal` and the same `--rethink` flag. The desktop agent adds `--rethink-attempts` and `--rethink-timeout` and stalls after 3 actions without observed progress. The browser front takes the same three names; `docs/browser-front.md` decision 19 describes its branch. A rail takes -`--model jev|clm|laya|laya-served`, the models that answer `noul`. +`--model jev|clm|laya|laya-served|clef`, the models that answer `noul`. `uv run python -m evals.table evals/results` aggregates every job folder per eval and model into one table. Every `run` prints one JSON object on stdout and nothing else there; `s1a-mcp` serves the same agents over stdio diff --git a/docs/architecture.md b/docs/architecture.md index 09e67a9..fec295a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -51,10 +51,11 @@ validation; `docs/decision-models.md`), `s1a/decision_models/wire.py` (the HTTP | `cua` | [Cua-S1 Nano](https://huggingface.co/cua-ai/cua-s1-nano-0.1) (`cua-ai/cua-s1-nano-0.1`, 855K) | in process, `uv sync --extra cua`; no key | a 256-byte context (header, goal, state, then rules), 96 bytes per option | | `omnijev` | [OmniJev](https://github.com/tinnel123666888/OmniJev) (Qwen3.5 VL, 0.8B by default, 2B or 4B) | in process, browser agents only, `uv sync --extra omnijev` and a clone named by `OMNIJEV_REPO`; no key; a GPU for useful speed | a viewport screenshot per tick, plus the text state (recent actions first, page text capped at 2,000 characters) | | `onejev` | [OneJev](https://github.com/OmniJev/OneJev) (0.8B–27B, Apache-2.0) via `qev`/`flide` | served HTTP, browser agents only; `ONEJEV_URL`; no cloud key | a viewport screenshot per tick as `media` with `` in state | +| `clef` | [Clef](https://huggingface.co/Cloudflare/clef) / Clef-flash (Apache-2.0) | served HTTP: `CLEF_URL` (local `/v1/systemone`) or Workers AI (`CLOUDFLARE_ACCOUNT_ID` + `CLOUDFLARE_AUTH_TOKEN`); `CLEF_MODEL` selects `clef` or `clef-flash` | text state; optional screenshots as Clef `images` (max 4). No `score` questions or `videos` on our interface | | `random`, `rule` | the tool front's two baselines | in process | the candidates | | `llm` | the chat model | for the comparison columns | the transcript | -`decision_models.build_model(model_name)` builds the first six; `llm` is not a decision model. +`decision_models.build_model(model_name)` builds every `--model` name except `llm`, which is not a decision model. ## Entry points @@ -64,7 +65,7 @@ the first import of both, routes the harness logs to files under `runs/logs` bef MCP stdio protocol only. Every `run` prints one JSON object on stdout: a tool agent's series summary with its `job_dir`, a browser agent's -answer, a rail's evaluation. A browser agent takes `--model jev|laya|cua|omnijev|onejev|llm`; its policy switches are run-time flags: +answer, a rail's evaluation. A browser agent takes `--model jev|laya|cua|omnijev|onejev|clef|llm`; its policy switches are run-time flags: `--batch on|off`, `--prefetch on|off`, `--goal-values on|off`. `s1a-mcp` serves the same agents to an MCP host over stdio, one Runner for the server's lifetime and one run at a time. `uv run python -m evals.table evals/results` aggregates every job folder per eval and model into one table. `scripts/showcase.sh` plays one visual episode per @@ -73,7 +74,7 @@ eval and model outside the matrix and `python -m evals.replay` renders a pair si Every tool agent, `desktop` included, takes `--model jev|laya|cua|llm|random|rule`, `--rethink on|off`, `--episodes N`, `--seed S`, `--max-steps`, `--timeout` and `--headed`, and writes a Harbor-shaped job folder under -`evals/results//`. Every browser agent takes `--model jev|laya|cua|omnijev|onejev|llm` and `--goal`. A rail takes +`evals/results//`. Every browser agent takes `--model jev|laya|cua|omnijev|onejev|clef|llm` and `--goal`. A rail takes `--model jev|laya`, the two models that answer `noul`. `decide` and `probe` take `--model jev|laya|cua`. On a browser agent `laya` needs `LAYA_MAX_LEN` raised to the page's size; `cua` reads a 256-byte context (header, goal, state, then rules) and 96 bytes per option, a baseline on any page. Exit codes: 0 for a finished run, including one whose diff --git a/docs/capabilities.md b/docs/capabilities.md index f427af6..063a144 100644 --- a/docs/capabilities.md +++ b/docs/capabilities.md @@ -17,6 +17,7 @@ For issue trackers and serving support, see [System1-Omni model tracker #83](htt | LAYA (`--model laya-served`; served checkpoint/revision is reported by the endpoint) | Text | `choice`, `noul` | Tool, browser, rails, `decide`/`probe`, MCP | Agents HTTP client can connect directly to a Laya worker or through System1-Omni `omni-jev` at `/v1/systemone` | Historical direct-worker and Omni-front MPS ticket-router measurements are recorded below (90 decisions/configuration, 63 correct each); historical CPU served request replay is separate and is not task-success evidence. Other hardware/checkpoints unverified. | | OmniJev (`--model omnijev`; default `tinnel123/OmniJev-0.8B@v1.1` on `Qwen/Qwen3.5-0.8B`; configurable 2B/4B) | Screenshot plus text state/context | `choice`, `noul` | Browser front via `s1a run` and MCP `run_agent`; direct `build_model()` factory path. Not registered in tool/rails, CLI `decide`/`probe`, or MCP `decide` | In-process OmniJev clone via `MSO1.system_one`; no System1-Omni served vision path | Historical A100 80 GB 4B runs, Windows 11 CPU 0.8B runs, and A40 46 GB 4B runs are detailed below. They do not establish broad task success; current-main reproduction unverified. | | OneJev (`--model onejev`; default request id `OmniJev/OneJev1.6-4B`; set `ONEJEV_MODEL`) | Screenshot(s) plus text state/context via TypeSafe `media` / `` | `choice`, `noul` | Browser front via `s1a run` and MCP `run_agent`; direct `build_model()` factory path. Not registered in tool/rails, CLI `decide`/`probe`, or MCP `decide` | HTTP client to `qev`/`flide` at `ONEJEV_URL` (`POST /v1/systemone` + `media`) | Contract tests use a fake HTTP server. Live GPU / GGUF hardware validation **not recorded in this checkout** (#88). | +| Clef / Clef-flash (`--model clef`; variant via `CLEF_MODEL`, default `clef-flash`) | Text state, plus up to 4 PNG/JPEG/WebP screenshots in Clef's `images` array when present; an observation without an image still runs as text. `videos` are unsupported on our interface (the Workers AI Clef / Clef-flash input schema also has no `videos` field; that extension is documented on Clef-omni). | `choice`, `noul`. Clef's protocol also defines `score`, but Agents has no corresponding question type and this adapter does not send `score` questions. | Tool, browser, rails, CLI `decide`/`probe`, MCP `decide`, and `build_model()`. | HTTP to a local SGLang `/v1/systemone` server at `CLEF_URL`, or to Cloudflare Workers AI (`CLOUDFLARE_ACCOUNT_ID` + `CLOUDFLARE_AUTH_TOKEN`) at `POST /client/v4/accounts/$ACCOUNT_ID/ai/run/@cf/cloudflare/clef` or `clef-flash`. | **Adapter wired.** Contract tests use a fake HTTP server (local body and the Workers AI REST envelope). Live Workers AI or local-GPU qualification on a named checkpoint and path is **not recorded in this checkout** (#126). Cloudflare Decision Index and workflow-eval numbers are not Agents results and are not copied here. | | Cua-S1 Nano (`cua-ai/cua-s1-nano-0.1/text`, `--model cua`, default variant) | Text | `choice` only | Tool/browser paths where registered; no screenshot input | In-process `cua_s1.nano.NanoScorer` | No real Nano inference artifact found in this checkout. **CPU/GPU/MPS unverified here.** | | Cua-S1 4B 0.2 text adapter (`Qwen/Qwen3.5-4B` + `cua-ai/cua-s1-4b-0.2/text`, `CUA_S1_VARIANT=4b`, `CUA_S1_MODALITY=text`) | Text | `choice` only | Tool decisions and text-only client paths; desktop option grounding is implemented | In-process Transformers/PEFT scorer | Contract tests use a fake scorer; real checkpoint/device validation **not present in this checkout**. | | Cua-S1 4B 0.2 multimodal adapter (`Qwen/Qwen3.5-4B` + `cua-ai/cua-s1-4b-0.2/multimodal`, variant `4b`) | One current screenshot plus text task/context | `choice` only; maximum 26 options in text and multimodal modes; multimodal requires exactly one screenshot | Screenshot-dependent desktop decision adapter; this does not itself complete the Omni capture/execute bridge | In-process Transformers/PEFT scorer with screenshot passed as a temporary file | Contract tests use a fake scorer; separate historical external evidence reports a bounded MPS fixture run (see below). Current-main reproduction and CUDA validation remain unverified. | diff --git a/docs/configuration.md b/docs/configuration.md index e03db7c..f7f66de 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -57,6 +57,12 @@ Variables can be exported in your shell or placed in a `.env` file at the root o | `ONEJEV_MODEL` | `onejev` model | `OmniJev/OneJev1.6-4B` | Model id sent in the `/v1/systemone` body (checkpoint the server loaded, e.g. `OmniJev/OneJev1.6-0.8B`). | | `ONEJEV_API_KEY` | `onejev` model | *(unset)* | Bearer token when the server expects one; loopback `qev`/`flide` usually needs none. | | `ONEJEV_TIMEOUT_S` | `onejev` model | `30` | Deadline per decision in seconds, the one refused-connection / 502 / 504 retry included. A finite number above 0. Raise for large checkpoints or a cold load. | +| `CLEF_URL` | `clef` model | *(unset)* | Base URL of a local Clef / Clef-flash server, e.g. `http://127.0.0.1:30000`. Posts to `{CLEF_URL}/v1/systemone`. When set, this wins over Workers AI credentials. Required unless `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_AUTH_TOKEN` are set. | +| `CLOUDFLARE_ACCOUNT_ID` | `clef` model | *(unset)* | Cloudflare account id for Workers AI (`POST /client/v4/accounts/$ACCOUNT_ID/ai/run/@cf/cloudflare/clef` or `clef-flash`). Used only when `CLEF_URL` is unset. | +| `CLOUDFLARE_AUTH_TOKEN` | `clef` model | *(unset)* | Bearer token with Workers AI permission, as in the official Clef docs. `CLOUDFLARE_API_TOKEN` is accepted as an alias. Used only when `CLEF_URL` is unset. | +| `CLEF_MODEL` | `clef` model | `clef-flash` | Variant sent in the request body and, on Workers AI, selected in the run URL: `clef` (27B) or `clef-flash` (9B, default for latency). Other values are a configuration error. | +| `CLEF_API_KEY` | `clef` model | *(unset)* | Bearer token for a local `/v1/systemone` server when it expects one; loopback SGLang usually needs none. | +| `CLEF_TIMEOUT_S` | `clef` model | `30` | Deadline per decision in seconds, the one refused-connection / 502 / 504 retry included. A finite number above 0. | | `CUA_DRIVER_BIN` | `desktop` agent | `cua-driver` | Path to the `cua-driver` executable on Windows or macOS when not located on `PATH`. | | `CUA_DRIVER_PERMISSION_MODE` | `desktop` agent | `standard` | Permission mode passed to `cua-driver mcp` (`standard`, or `bounded` for restricted capability manifests). | | `HF_HOME` | Hugging Face runtime | `~/.cache/huggingface` | Cache directory where Laya and Cua-S1 checkpoints are downloaded on first run. | diff --git a/docs/decision-models.md b/docs/decision-models.md index 0ca3c5b..da73339 100644 --- a/docs/decision-models.md +++ b/docs/decision-models.md @@ -12,7 +12,7 @@ TypeSafe "System One model". This repository uses the terms interchangeably. `-- `clm` (CLM's `clm-serve` over HTTP, see [clm.md](clm.md)), `laya` (in process, behind `uv sync --extra laya`), `laya-served` (Laya served over HTTP by system1-omni, see [served-laya.md](served-laya.md)), `cua` (Cua-S1 Nano in process, behind `uv sync --extra cua`), -`onejev` (OneJev over HTTP via `qev`/`flide` with a screenshot), `random` and `rule` (the tool front's baselines). +`onejev` (OneJev over HTTP via `qev`/`flide` with a screenshot), `clef` (Clef / Clef-flash over Workers AI or a local `/v1/systemone` server), `random` and `rule` (the tool front's baselines). `build_model(model_name, seed=, rule=)` builds one from the environment; `llm` names the chat model, which `build_model` does not build. The registered paths, input modalities and question types are summarized in the [decision-model capability matrix](capabilities.md), separately from run evidence and hardware validation. @@ -66,6 +66,7 @@ shorthands; `warm()` and `close()` open and release the backend. | `cua` | `CuaS1Model(scorer, collator, model=, context_bytes=, option_bytes=)` | `cua` | Cua-S1 Nano, one `score_elements` pass per request on a thread; choice questions only, text only, deterministic; the context is header, state and rules; the checkpoint reads its first 256 bytes, and the first overflowing request logs one warning; `from_env` reads `CUA_S1_*` (see [configuration.md](configuration.md)) | | `omnijev` | `OmniJevModel(agent, model=)` | `omnijev` | OmniJev (a Qwen3.5 vision-language decision model), one `MSO1.system_one` call per request on a thread; choice and noul questions over the observation's screenshot, deterministic; the text state, goal and rules go in front of each question (a browser state puts its recent actions first and caps the page text at 2,000 characters, so a long page cannot push the history out of the 6,000-character context), a browser element row becomes its label and value; a choice's probabilities, which OmniJev leaves `abstain` out of, are renormalised over the offered keys; an observation without an image is `MODEL_CALL_FAILED`; `from_env` reads `OMNIJEV_*` (see [configuration.md](configuration.md)); in process only: system1-omni has no OmniJev vision worker yet (its supported models are Laya, Open-Jev text and Cua-S1 screenshots), so there is no served `omnijev` path | | `onejev` | `OneJevModel(client, model=)` | `onejev` | OneJev (OmniJev org, Apache-2.0) served by `qev`/`flide` over TypeSafe-compatible `POST /v1/systemone` plus a `media` field; choice and noul over the observation's screenshot(s), deterministic; state carries `` markers and each screenshot is a PNG/JPEG/WebP data URL in `media` (digest and size in `raw.sent_images`, never the bytes); an observation without an image is `MODEL_CALL_FAILED` (same policy as `omnijev`); one refused-connection / 502 / 504 retry within `ONEJEV_TIMEOUT_S`; `raw` keeps `served_by`, `url`, `request_id` and `server_timing`; `from_env` reads `ONEJEV_*` (see [configuration.md](configuration.md)); browser and `build_model` only — not tool/rails/`decide`. Local tests use a stub server; live GPU validation is **not recorded** in this checkout | +| `clef` | `ClefModel(client, model=)` | `clef` | [Clef](https://huggingface.co/Cloudflare/clef) / [Clef-flash](https://huggingface.co/Cloudflare/clef-flash) (Cloudflare, Apache-2.0) served over HTTP: Cloudflare Workers AI (`POST /client/v4/accounts/$ACCOUNT_ID/ai/run/@cf/cloudflare/clef` or `clef-flash`) or a local SGLang `POST /v1/systemone`. Variant via `CLEF_MODEL=clef` or `clef-flash` (default `clef-flash`). Choice and noul only — Clef's `score` type is unsupported on our interface and is not sent. Screenshots map to Clef's `images` array (PNG/JPEG/WebP data URLs, max 4 per the Workers AI schema; digests in `raw.sent_images`, never the bytes); an observation without an image runs as text. `videos` are unsupported on our interface; the Workers AI Clef / Clef-flash input schema also has no `videos` field (that extension is documented on Clef-omni) and this adapter does not send one. One refused-connection / 502 / 504 retry within `CLEF_TIMEOUT_S`; `raw` keeps `served_by` (including `path`: `local` or `workers-ai`), `url`, `request_id` and `server_timing`. `from_env` reads `CLEF_URL` or `CLOUDFLARE_ACCOUNT_ID` + `CLOUDFLARE_AUTH_TOKEN` (see [configuration.md](configuration.md)). Registered on the tool, browser, rails, `decide`/`probe` and MCP fronts. Contract tests use a stub server; live Workers AI / GPU qualification is **not recorded** in this checkout | | `random` | `RandomModel(seed)` | `random` | uniform over the offered keys (contract confidence = `1/|options|`), one seeded stream per episode; choice questions only | | `rule` | `RuleModel(name, rule)` | the rule's name | one-hot, confidence 1; a key outside the menu raises `RuntimeError`, a bug in the rule | @@ -191,6 +192,28 @@ real servers in `tests/data/served_laya/`. Nothing patches `httpx`. fails on missing keys (`strict=True` or an equivalent check). Prefer fixing this in the model's package; Laya added the skip in 0.3.9. This step does not apply to backends served over HTTP. +### Served Clef / Clef-flash + +`clef` is registered in `build_model()` and on the tool, browser, rails, `decide`/`probe` and MCP fronts. Point +`CLEF_URL` at a local [SGLang Clef](https://huggingface.co/Cloudflare/clef) server, or set `CLOUDFLARE_ACCOUNT_ID` +and `CLOUDFLARE_AUTH_TOKEN` for [Workers AI](https://developers.cloudflare.com/workers-ai/models/clef/). +`CLEF_MODEL` selects `clef` (27B) or `clef-flash` (9B, the default). The request `model` field is that same +selector (`clef` / `clef-flash`), which is what the Workers AI schema requires and what the in-process `systemone` +example on the model card uses. The model card's SGLang curl shows `Cloudflare/clef` as the model id; this adapter +does not remap the selector to a Hugging Face id. Example (not run in CI; needs a local server or a Cloudflare +token, and is not a qualification record): + +```bash +# local SGLang, as on the Clef model card +# docker run --gpus all -p 30000:30000 lmsysorg/sglang:dev-clef sglang serve --model-path Cloudflare/clef-flash --host 0.0.0.0 --port 30000 +CLEF_URL=http://127.0.0.1:30000 CLEF_MODEL=clef-flash \ + uv run s1a probe path/to/cases.jsonl --model clef +``` + +The capability matrix distinguishes this **adapter wiring** from qualification on a named checkpoint and path: +no live Workers AI or GPU run is recorded in this checkout, and Cloudflare's Decision Index / workflow-eval +numbers are not Agents results. + ### Laya browser input shaping Laya is text only and reads a 512 to 1024 token window; it fits the tool front first. The browser front's element diff --git a/s1a/browser/browse.py b/s1a/browser/browse.py index 81adfed..f93927b 100644 --- a/s1a/browser/browse.py +++ b/s1a/browser/browse.py @@ -49,6 +49,7 @@ "cua", "omnijev", "onejev", + "clef", "llm", ) # a decision model over HTTP or in process, or the chat model RUNS_DIR = HOME / "runs" / "browser" @@ -254,7 +255,7 @@ async def browse( workspace = str(logs_dir / "workspace") # the harness scaffolds SOUL.md, memory/ and friends here, not in the cwd instance = BrowserInstanceConfig(launch_args=browser_launch_args(headless)) match model_name: - case "jev" | "jev-vl-served" | "clm" | "laya" | "laya-served" | "cua" | "omnijev" | "onejev": + case "jev" | "jev-vl-served" | "clm" | "laya" | "laya-served" | "cua" | "omnijev" | "onejev" | "clef": if decision_model is None: raise RuntimeError(f"--model {model_name} needs a decision model") slot_model = BrowserDecisionModel( @@ -321,7 +322,7 @@ def parser(spec: BrowserAgentSpec) -> argparse.ArgumentParser: "--model", choices=BROWSER_MODEL_NAMES, required=True, - help="who decides each browser step: jev, jev-vl-served, clm, laya-served or onejev (over HTTP; jev-vl-served and onejev require a screenshot), laya, cua or omnijev (in process; omnijev reads a screenshot), or llm (the chat model in MODEL_NAME)", + help="who decides each browser step: jev, jev-vl-served, clm, laya-served, onejev or clef (over HTTP; jev-vl-served and onejev require a screenshot; clef sends images when present), laya, cua or omnijev (in process; omnijev reads a screenshot), or llm (the chat model in MODEL_NAME)", ) build.add_argument( "--goal", default=spec.goal, required=spec.goal is None, help="the task; the spec's goal when it has one" diff --git a/s1a/cli.py b/s1a/cli.py index 6a868f8..8152181 100644 --- a/s1a/cli.py +++ b/s1a/cli.py @@ -25,6 +25,7 @@ "laya", "laya-served", "cua", + "clef", ) # the decision models that answer one question on their own: no env, no rule, no chance @@ -40,7 +41,7 @@ def parser() -> argparse.ArgumentParser: run.add_argument("flags", nargs=argparse.REMAINDER) decide = commands.add_parser( "decide", - help="one choice question to a decision model: jev, clm or laya-served over HTTP, or laya and cua in process", + help="one choice question to a decision model: jev, clm, laya-served or clef over HTTP, or laya and cua in process", ) decide.add_argument("--state", required=True, help="a JSON object, or @path to a file holding one") decide.add_argument( @@ -55,7 +56,7 @@ def parser() -> argparse.ArgumentParser: "--model", choices=DECIDE_MODEL_NAMES, default="jev", - help="who answers: jev, clm or laya-served over HTTP, laya and cua in process", + help="who answers: jev, clm, laya-served or clef over HTTP, laya and cua in process", ) fit = commands.add_parser("probe", help="the fit probe: hand-written choice cases from a JSONL file") fit.add_argument( @@ -67,7 +68,7 @@ def parser() -> argparse.ArgumentParser: "--model", choices=DECIDE_MODEL_NAMES, default="jev", - help="who answers: jev, clm or laya-served over HTTP, laya and cua in process", + help="who answers: jev, clm, laya-served or clef over HTTP, laya and cua in process", ) fit.add_argument( "--order", diff --git a/s1a/decision_models/__init__.py b/s1a/decision_models/__init__.py index b3bdab2..528c0d6 100644 --- a/s1a/decision_models/__init__.py +++ b/s1a/decision_models/__init__.py @@ -9,6 +9,7 @@ from s1a.decision_models.base import DecisionModel, JevTransport from s1a.decision_models.baselines import RandomModel, Rule, RuleModel +from s1a.decision_models.clef import ClefModel from s1a.decision_models.cua import CuaS1Model from s1a.decision_models.factory import DECISION_MODEL_NAMES, build_model from s1a.decision_models.fakes import ScriptedModel, ScriptedTransport @@ -48,6 +49,7 @@ "ScriptedTransport", "Choice", "ChoiceQuestion", + "ClefModel", "CuaS1Model", "Decision", "Image", diff --git a/s1a/decision_models/clef.py b/s1a/decision_models/clef.py new file mode 100644 index 0000000..397d5fe --- /dev/null +++ b/s1a/decision_models/clef.py @@ -0,0 +1,421 @@ +# coding: utf-8 +"""Clef / Clef-flash served over HTTP: Workers AI or a local ``/v1/systemone`` server. + +Clef and Clef-flash (https://huggingface.co/Cloudflare/clef, Apache-2.0) are multimodal System One decision +models. Workers AI is ``POST /client/v4/accounts/$ACCOUNT_ID/ai/run/@cf/cloudflare/clef`` (or ``clef-flash``) +with a Cloudflare token; a local SGLang server (``lmsysorg/sglang:dev-clef``) speaks ``POST /v1/systemone``. +Screenshots travel in Clef's ``images`` array (PNG/JPEG/WebP data URLs, max 4). An observation without an image +runs as text. This adapter never loads weights. ``score`` questions and ``videos`` are out of scope: Agents has +no ``ScoreQuestion`` or video observation, and the Workers AI Clef / Clef-flash input schema has no ``videos`` +field (that extension is documented on Clef-omni). +""" + +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import logging +import math +import os +import time +import uuid +from collections.abc import Callable +from datetime import datetime, timezone + +import httpx + +from openjiuwen.core.common.exception.codes import StatusCode +from openjiuwen.core.common.exception.errors import BaseError, build_error + +from s1a.decision_models.base import DecisionModel +from s1a.decision_models.omnijev import omnijev_option +from s1a.decision_models.served import parse_server_timing +from s1a.decision_models.types import ( + ChoiceQuestion, + Image, + Json, + NoulQuestion, + Observation, + Question, + Reply, + Usage, +) + +logger = logging.getLogger(__name__) + +CLEF_MODELS = ("clef", "clef-flash") +DEFAULT_CLEF_MODEL = "clef-flash" # the 9B variant; set CLEF_MODEL=clef for the 27B model +CLEF_TIMEOUT_S = 30.0 +CLEF_HEALTH_TIMEOUT_S = 2.0 +MAX_CLEF_IMAGES = 4 # Workers AI schema: images.maxItems = 4 +WORKERS_AI_RUN = "https://api.cloudflare.com/client/v4/accounts/{account}/ai/run/@cf/cloudflare/{model}" +_MEDIA_TYPES = frozenset({"image/png", "image/jpeg", "image/webp"}) +_RETRIED_TRANSPORT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.RemoteProtocolError, httpx.ReadError) +_RETRIED_STATUSES = frozenset({502, 504}) +_NOT_UP_LOCAL = ( + "a Clef server listens at /v1/systemone once the checkpoint is loaded; start it per " + "https://huggingface.co/Cloudflare/clef (lmsysorg/sglang:dev-clef) and point CLEF_URL at it" +) +_NOT_UP_WORKERS = ( + "Workers AI needs a token with Workers AI permission; see https://developers.cloudflare.com/workers-ai/models/clef/" +) + + +def workers_ai_url(account_id: str, model: str) -> str: + """The official Workers AI run URL for ``clef`` or ``clef-flash``.""" + if model not in CLEF_MODELS: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg=f"CLEF_MODEL must be clef or clef-flash, not {model!r}", + ) + return WORKERS_AI_RUN.format(account=account_id, model=model) + + +def clef_image(image: Image) -> tuple[str, Json]: + """One Clef ``images`` data URL and the digest the step record keeps instead of the bytes. + + Official Workers AI schema: ``data:image/png;base64,...`` (or jpeg / webp). Remote URLs are not accepted. + """ + if image.media_type not in _MEDIA_TYPES: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + error_msg=f"clef cannot send media type {image.media_type!r}; use PNG, JPEG or WebP", + ) + if not image.data: + raise build_error(StatusCode.MODEL_CALL_FAILED, error_msg="clef cannot send an empty screenshot") + data_uri = f"data:{image.media_type};base64,{base64.b64encode(image.data).decode('ascii')}" + record: Json = { + "sha256": hashlib.sha256(image.data).hexdigest(), + "media_type": image.media_type, + "bytes": len(image.data), + } + return data_uri, record + + +def clef_images(images: tuple[Image, ...]) -> tuple[list[str], list[Json]]: + """Every screenshot as a data URL, or a call failure past the Workers AI max of four.""" + if len(images) > MAX_CLEF_IMAGES: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + error_msg=f"clef accepts at most {MAX_CLEF_IMAGES} images per the Workers AI schema, not {len(images)}", + ) + urls: list[str] = [] + records: list[Json] = [] + for image in images: + url, record = clef_image(image) + urls.append(url) + records.append(record) + return urls, records + + +def clef_question(question: Question) -> Json: + """Choice / noul in Clef's System One shape: string instructions, flattened option labels. + + Clef's Workers AI schema requires ``instructions`` and, for a choice, ``criteria``. Browser element rows become + their label and value (the same flattening ``omnijev_option`` already does); we do not send ``score`` questions + or a ``videos`` field. + """ + match question: + case ChoiceQuestion(): + parts = [question.goal, question.operation, *question.rules] + return { + "type": "choice", + "instructions": "\n".join(part for part in parts if part) or "Which option comes next?", + "criteria": {key: omnijev_option(description) for key, description in question.options.items()}, + } + case NoulQuestion(): + body: Json = {"type": "noul", "instructions": question.question} + if question.criteria: + body["criteria"] = dict(question.criteria) + return body + raise TypeError(f"not a question: {question!r}") + + +def clef_payload(body: object) -> Json: + """The System One decision object: used as-is, or unwrapped from the Workers AI REST envelope. + + Local ``/v1/systemone`` returns ``{model, answers, usage}``. The Workers AI REST API wraps that as + ``{success, result, errors, messages}`` (https://developers.cloudflare.com/workers-ai/get-started/rest-api/). + Missing or malformed answers fail closed; a ``success: false`` envelope surfaces the Cloudflare errors. + """ + if not isinstance(body, dict): + raise build_error(StatusCode.MODEL_CALL_FAILED, error_msg="clef returned a malformed body") + if isinstance(body.get("answers"), dict): + return body + result = body.get("result") + if isinstance(result, dict) and isinstance(result.get("answers"), dict): + return result + if body.get("success") is False: + errors = body.get("errors") + detail = errors if errors else body + raise build_error( + StatusCode.MODEL_CALL_FAILED, + error_msg=f"Workers AI rejected the Clef request: {detail!r}"[:400], + ) + raise build_error(StatusCode.MODEL_CALL_FAILED, error_msg="clef returned no answers object") + + +class ClefClient: + """HTTP to one Clef endpoint: one deadline per decision, one transport / 502 / 504 retry.""" + + def __init__( + self, + *, + url: str, + endpoint: str, + api_key: str | None = None, + timeout_s: float = CLEF_TIMEOUT_S, + transport: httpx.AsyncBaseTransport | None = None, + clock: Callable[[], float] = time.monotonic, + health_url: str | None = None, + path: str = "local", + ) -> None: + if not math.isfinite(timeout_s) or timeout_s <= 0: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg=f"timeout_s must be a finite number above 0, not {timeout_s!r}", + ) + self.url = url.rstrip("/") + self.endpoint = endpoint + self.health_url = health_url + self.path = path + self._timeout_s = timeout_s + self._clock = clock + self._not_up = _NOT_UP_WORKERS if path == "workers-ai" else _NOT_UP_LOCAL + headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} + self._client = httpx.AsyncClient(timeout=timeout_s, headers=headers, transport=transport) + + async def warm(self) -> Json: + """``GET /health`` on a local server; Workers AI has no health route, so this is a no-op there.""" + if not self.health_url: + return {} + try: + response = await asyncio.wait_for( + self._client.get(self.health_url, timeout=CLEF_HEALTH_TIMEOUT_S), CLEF_HEALTH_TIMEOUT_S + ) + except (httpx.ConnectError, httpx.ConnectTimeout) as exc: + raise build_error( + StatusCode.MODEL_CALL_FAILED, cause=exc, error_msg=f"no served Clef at {self.url}: {self._not_up}" + ) from exc + except (TimeoutError, httpx.HTTPError) as exc: + raise build_error( + StatusCode.MODEL_CALL_FAILED, cause=exc, error_msg=f"served Clef at {self.url} did not answer: {exc}" + ) from exc + if response.is_error: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + error_msg=f"served Clef at {self.url} returned HTTP {response.status_code}", + ) + try: + body = response.json() + except ValueError as exc: + raise build_error( + StatusCode.MODEL_CALL_FAILED, cause=exc, error_msg="served Clef returned a malformed body" + ) from exc + return body if isinstance(body, dict) else {} + + async def decide(self, body: Json, request_id: str) -> tuple[Json, int, dict[str, str]]: + """One decision: the unwrapped payload, its round trip in ms and the response headers.""" + headers = {"X-Request-Id": request_id} + deadline = self._clock() + self._timeout_s + retried = False + while True: + remaining = deadline - self._clock() + if remaining <= 0: + raise self._no_answer(None) + started = time.perf_counter() + post = self._client.post(self.endpoint, json=body, headers=headers, timeout=remaining) + try: + response = await asyncio.wait_for(post, remaining) + except TimeoutError as exc: + raise self._no_answer(exc) from exc + except _RETRIED_TRANSPORT as exc: + if not retried: + retried = True + continue + if isinstance(exc, httpx.ConnectError): + raise build_error( + StatusCode.MODEL_CALL_FAILED, + cause=exc, + error_msg=f"no served Clef at {self.url}: {self._not_up}", + ) from exc + raise build_error( + StatusCode.MODEL_CALL_FAILED, + cause=exc, + error_msg=f"served Clef unreachable at {self.url}: {exc}", + ) from exc + except httpx.HTTPError as exc: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + cause=exc, + error_msg=f"served Clef call failed at {self.url}: {exc}", + ) from exc + ms = round((time.perf_counter() - started) * 1000) + if response.status_code in _RETRIED_STATUSES and not retried: + retried = True + continue + if response.is_error: + raise build_error( + StatusCode.MODEL_CALL_FAILED, + error_msg=f"served Clef failed (HTTP {response.status_code}): {response.text[:200].strip()}", + ) + try: + raw = response.json() + except ValueError as exc: + raise build_error( + StatusCode.MODEL_CALL_FAILED, cause=exc, error_msg="served Clef returned a malformed body" + ) from exc + return clef_payload(raw), ms, dict(response.headers) + + def _no_answer(self, cause: Exception | None) -> Exception: + return build_error( + StatusCode.MODEL_CALL_FAILED, + cause=cause, + error_msg=f"no answer from served Clef at {self.url} within {self._timeout_s:g} s; {self._not_up}", + ) + + async def close(self) -> None: + await self._client.aclose() + + +class ClefModel(DecisionModel): + """Clef behind Workers AI or ``/v1/systemone``: choice and noul; images when the observation has them.""" + + name = "clef" + supports_images = True + deterministic = True + bills_input_tokens = False # do not price Clef at Jev's rate; Workers AI has its own list price + + def __init__(self, client: ClefClient, *, model: str = DEFAULT_CLEF_MODEL) -> None: + if model not in CLEF_MODELS: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg=f"CLEF_MODEL must be clef or clef-flash, not {model!r}", + ) + self._client = client + self._model = model + self._served: Json = {} + self._served_at: str | None = None + self._warmed = False + + @property + def model(self) -> str: + return self._model + + async def warm(self) -> None: + self._served = await self._client.warm() + self._served_at = datetime.now(timezone.utc).isoformat(timespec="seconds") + self._warmed = True + + def _served_by(self) -> Json: + return { + "url": self._client.url, + "path": self._client.path, + "checkpoint": self._served.get("model") or self._served.get("checkpoint") or self._model, + "device": self._served.get("device"), + "source": "health" if self._client.health_url else self._client.path, + "read_at": self._served_at, + } + + async def _warm_once(self) -> None: + if self._warmed or not self._client.health_url: + return + try: + await self.warm() + except BaseError as exc: + logger.warning("[clef] could not read /health at %s: %s", self._client.url, exc) + + async def _decide(self, observation: Observation, questions: dict[str, Question]) -> Reply: + body: Json = { + "model": self._model, + "state": observation.state, + "questions": {name: clef_question(question) for name, question in questions.items()}, + } + records: list[Json] = [] + if observation.images: + urls, records = clef_images(observation.images) + body["images"] = urls + await self._warm_once() + request_id = uuid.uuid4().hex + payload, ms, headers = await self._client.decide(body, request_id) + answers = payload["answers"] + lower = {key.lower(): value for key, value in headers.items()} + raw: Json = { + **payload, + "url": self._client.url, + "request_id": request_id, + "served_by": self._served_by(), + "server_timing": parse_server_timing(lower.get("server-timing")), + } + if lower.get("cf-ray"): + raw["cf_ray"] = lower["cf-ray"] + if records: + raw["sent_images"] = records + return Reply( + answers={name: answers[name] for name in questions if name in answers}, + latency_ms=ms, + usage=Usage.from_payload(payload.get("usage")), + model=str(payload.get("model") or self._model), + raw=raw, + ) + + async def close(self) -> None: + await self._client.close() + + @classmethod + def from_env(cls) -> "ClefModel": + """``CLEF_URL`` (local ``/v1/systemone``) or ``CLOUDFLARE_ACCOUNT_ID`` + ``CLOUDFLARE_AUTH_TOKEN``. + + ``CLEF_MODEL`` is ``clef`` or ``clef-flash`` (default ``clef-flash``). ``CLEF_URL`` wins when both a local + URL and Cloudflare credentials are set. ``CLOUDFLARE_API_TOKEN`` is accepted as an alias for the official + Clef-docs name ``CLOUDFLARE_AUTH_TOKEN``. Optional ``CLEF_API_KEY`` / ``CLEF_TIMEOUT_S`` for the local path. + """ + model = (os.getenv("CLEF_MODEL") or DEFAULT_CLEF_MODEL).strip() + if model not in CLEF_MODELS: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg=f"CLEF_MODEL must be clef or clef-flash, not {model!r}", + ) + try: + timeout_s = float(os.getenv("CLEF_TIMEOUT_S") or CLEF_TIMEOUT_S) + except ValueError as exc: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, cause=exc, error_msg="CLEF_TIMEOUT_S must be a number" + ) from exc + if not math.isfinite(timeout_s) or timeout_s <= 0: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg="CLEF_TIMEOUT_S must be a finite number above 0", + ) + url = (os.getenv("CLEF_URL") or "").strip() + if url: + base = url.rstrip("/") + client = ClefClient( + url=base, + endpoint=f"{base}/v1/systemone", + api_key=os.getenv("CLEF_API_KEY") or None, + timeout_s=timeout_s, + health_url=f"{base}/health", + path="local", + ) + return cls(client, model=model) + account = (os.getenv("CLOUDFLARE_ACCOUNT_ID") or "").strip() + token = (os.getenv("CLOUDFLARE_AUTH_TOKEN") or os.getenv("CLOUDFLARE_API_TOKEN") or "").strip() + if not account or not token: + raise build_error( + StatusCode.MODEL_SERVICE_CONFIG_ERROR, + error_msg=( + "--model clef needs CLEF_URL (local /v1/systemone, e.g. http://127.0.0.1:30000) or " + "CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_AUTH_TOKEN (Workers AI)" + ), + ) + endpoint = workers_ai_url(account, model) + client = ClefClient( + url=endpoint, + endpoint=endpoint, + api_key=token, + timeout_s=timeout_s, + path="workers-ai", + ) + return cls(client, model=model) diff --git a/s1a/decision_models/factory.py b/s1a/decision_models/factory.py index ea1cf33..db11d21 100644 --- a/s1a/decision_models/factory.py +++ b/s1a/decision_models/factory.py @@ -7,6 +7,7 @@ from s1a.decision_models.base import DecisionModel from s1a.decision_models.baselines import RandomModel, Rule, RuleModel +from s1a.decision_models.clef import ClefModel from s1a.decision_models.clm import ClmModel from s1a.decision_models.cua import CuaS1Model from s1a.decision_models.cua_four_b import CuaFourBModel @@ -26,6 +27,7 @@ "cua", "omnijev", "onejev", + "clef", "random", "rule", ) # the names that build a decision model; ``llm`` is not one @@ -55,6 +57,8 @@ def build_model(model_name: str, *, seed: int = 0, rule: tuple[str, Rule] | None return OmniJevModel.from_env() # the OmniJev import happens inside; it decides over a screenshot case "onejev": return OneJevModel.from_env() # OneJev/qev over HTTP with media; screenshot required + case "clef": + return ClefModel.from_env() # Clef / Clef-flash over Workers AI or local /v1/systemone case "random": return RandomModel(seed) case "rule": diff --git a/s1a/mcp_server.py b/s1a/mcp_server.py index 53013ff..27f3061 100644 --- a/s1a/mcp_server.py +++ b/s1a/mcp_server.py @@ -31,7 +31,7 @@ "constraint puzzles or free-text generation. list_agents gives every agent's flags: a browser agent takes " "--model jev --goal '...' and needs a chat-model key (OPENAI_API_KEY or LLM_API_KEY plus MODEL_NAME), a Jev key " "(TYPESAFE_API_KEY or OPENROUTER_API_KEY) and Node for @playwright/mcp; a tool agent takes --model, --rethink and " - "--episodes; a rail takes --labelled-set. decide accepts model jev (default), clm, laya, cua or laya-served; local models " + "--episodes; a rail takes --labelled-set. decide accepts model jev (default), clm, laya, cua, laya-served or clef; local models " "need their optional extra and no Jev key, laya-served needs LAYA_SERVED_URL. run_agent reports progress per " "episode or browser step when the request carries a progressToken." ) @@ -182,12 +182,12 @@ async def decide( state: dict[str, Any], options: dict[str, str], rules: str, - model: Literal["jev", "clm", "laya", "laya-served", "cua"] = "jev", + model: Literal["jev", "clm", "laya", "laya-served", "cua", "clef"] = "jev", ) -> Decision: """One choice question: the chosen key, probabilities, confidence (= max p) and decision latency in ms. - Use jev over HTTP (default), laya/cua locally after installing the matching extra, or laya-served against a - running Laya server (LAYA_SERVED_URL). Local model loading + Use jev over HTTP (default), laya/cua locally after installing the matching extra, laya-served against a + running Laya server (LAYA_SERVED_URL), or clef against CLEF_URL or Workers AI. Local model loading is excluded from the reported latency. """ async with _one_at_a_time(f"decide ({model})"): diff --git a/s1a/rails.py b/s1a/rails.py index 29278cf..5187f87 100644 --- a/s1a/rails.py +++ b/s1a/rails.py @@ -31,7 +31,7 @@ from s1a.spec import Json, RailSpec, Verdict QUESTION = "check" -RAIL_MODEL_NAMES = ("jev", "clm", "laya", "laya-served") +RAIL_MODEL_NAMES = ("jev", "clm", "laya", "laya-served", "clef") BANDS = ("allow", "uncertain", "act", "failure") # a labelled-set row's outcome; failure: the decision itself failed @@ -266,7 +266,7 @@ def parser(spec: RailSpec) -> argparse.ArgumentParser: "--model", choices=RAIL_MODEL_NAMES, default="jev", - help="who answers the question: jev, clm or laya-served over HTTP, laya in process", + help="who answers the question: jev, clm, laya-served or clef over HTTP, laya in process", ) return build diff --git a/s1a/tool/loop.py b/s1a/tool/loop.py index 6c687f4..ee71a3a 100644 --- a/s1a/tool/loop.py +++ b/s1a/tool/loop.py @@ -28,7 +28,7 @@ from s1a.tool.rethink import RethinkRail from s1a.tool.models import ACT_TOOL, OBSERVE_TOOL, EvalState, ToolDecisionModel -MODEL_NAMES = ("jev", "clm", "llm", "random", "rule", "laya", "laya-served", "cua") +MODEL_NAMES = ("jev", "clm", "llm", "random", "rule", "laya", "laya-served", "cua", "clef") EVAL_PROMPT = ( "You play a game through two tools. Call observe first. Then call act with exactly one of the candidate keys the " "last tool result offered, one act per turn, until done is true. Then reply with one line: the final score." @@ -144,7 +144,7 @@ def build_slot_model( if chat is None: raise RuntimeError("--model llm needs the chat model: OPENAI_API_KEY or LLM_API_KEY, and MODEL_NAME") return chat - case "jev" | "clm" | "laya" | "laya-served" | "cua" | "random" | "rule": + case "jev" | "clm" | "laya" | "laya-served" | "cua" | "clef" | "random" | "rule": if decision_model is None: raise RuntimeError(f"--model {model_name} needs a decision model") return ToolDecisionModel(env, state, rules=rules, decision_model=decision_model, fallback=chat) diff --git a/s1a/tool/series.py b/s1a/tool/series.py index 42e59f2..7ad8093 100644 --- a/s1a/tool/series.py +++ b/s1a/tool/series.py @@ -26,7 +26,7 @@ def parser(spec: ToolAgentSpec) -> argparse.ArgumentParser: "--model", choices=MODEL_NAMES, required=True, - help="who decides: jev, clm or laya-served (over HTTP), laya or cua (in process), llm (the chat model in MODEL_NAME), random, or rule (the agent's baseline)", + help="who decides: jev, clm, laya-served or clef (over HTTP), laya or cua (in process), llm (the chat model in MODEL_NAME), random, or rule (the agent's baseline)", ) build.add_argument( "--rethink", @@ -96,7 +96,7 @@ async def play(spec: ToolAgentSpec, args: argparse.Namespace, *, results_dir: Pa limits = RecoveryLimits(max_attempts=attempts, timeout_s=float(rethink_timeout)) if args.model == "llm": raise RuntimeError("bounded rethink needs a decision model; --model llm cannot use it") - shared = build_model(args.model) if args.model in ("jev", "clm", "laya", "laya-served", "cua") else None + shared = build_model(args.model) if args.model in ("jev", "clm", "laya", "laya-served", "cua", "clef") else None run = await asyncio.to_thread(spec.series, args) # question fetches, game file parsing: seconds of blocking I/O if args.model == "rule": shared = build_model("rule", rule=run.baseline) diff --git a/tests/test_browse.py b/tests/test_browse.py index 37365df..e3354be 100644 --- a/tests/test_browse.py +++ b/tests/test_browse.py @@ -61,7 +61,7 @@ def test_a_timeout_or_max_steps_at_or_below_zero_is_a_usage_error(self) -> None: def test_the_model_flag_takes_a_decision_model_or_the_chat_model(self) -> None: self.assertEqual( browse.BROWSER_MODEL_NAMES, - ("jev", "jev-vl-served", "clm", "laya", "laya-served", "cua", "omnijev", "onejev", "llm"), + ("jev", "jev-vl-served", "clm", "laya", "laya-served", "cua", "omnijev", "onejev", "clef", "llm"), ) for model_name in browse.BROWSER_MODEL_NAMES: self.assertEqual(browse.parser(SPEC).parse_args(["--model", model_name, "--goal", "x"]).model, model_name) diff --git a/tests/test_clef_registration.py b/tests/test_clef_registration.py new file mode 100644 index 0000000..53e0fac --- /dev/null +++ b/tests/test_clef_registration.py @@ -0,0 +1,105 @@ +# coding: utf-8 +"""``clef`` is registered on the text fronts, the browser front, and the model factory.""" + +from __future__ import annotations + +import json +import os +import tempfile +from pathlib import Path +from unittest import IsolatedAsyncioTestCase, TestCase, mock + +from s1a.browser import browse +from s1a.browser.decision_model import BrowserPolicy +import typing + +from s1a import cli, mcp_server, rails +from s1a.decision_models import DECISION_MODEL_NAMES, build_model +from s1a.decision_models.fakes import ScriptedModel +from s1a.spec import BrowserAgentSpec, Budget +from s1a.tool import loop, series + + +def spec() -> BrowserAgentSpec: + return BrowserAgentSpec( + name="fixture", + description="A browser fixture", + rules="Choose an offered action", + language="en", + budget=Budget(max_steps=2, timeout_s=10, stall_after=0), + goal="Open the fixture", + ) + + +class TestClefRegistration(TestCase): + def test_factory_and_fronts_offer_the_backend(self) -> None: + self.assertIn("clef", DECISION_MODEL_NAMES) + self.assertIn("clef", browse.BROWSER_MODEL_NAMES) + self.assertIn("clef", cli.DECIDE_MODEL_NAMES) + self.assertIn("clef", loop.MODEL_NAMES) + self.assertIn("clef", rails.RAIL_MODEL_NAMES) + decide_model = typing.get_type_hints( + mcp_server.decide.__wrapped__ if hasattr(mcp_server.decide, "__wrapped__") else mcp_server.decide + )["model"] + self.assertIn("clef", typing.get_args(decide_model)) + args = browse.parser(spec()).parse_args(["--model", "clef"]) + self.assertEqual(args.model, "clef") + + +class TestClefEntrypoints(IsolatedAsyncioTestCase): + async def test_factory_builds_the_served_model_from_the_environment(self) -> None: + with mock.patch.dict(os.environ, {"CLEF_URL": "http://127.0.0.1:30000", "CLEF_TIMEOUT_S": "5"}): + model = build_model("clef") + try: + self.assertEqual(type(model).__name__, "ClefModel") + self.assertEqual(model.name, "clef") + self.assertEqual(model.model, "clef-flash") + self.assertTrue(model.supports_images) + self.assertTrue(model.deterministic) + finally: + await model.close() + + async def test_browser_routes_the_backend_to_the_decision_model_slot(self) -> None: + decision_model = ScriptedModel() + decision_model.name = "clef" + slot = mock.MagicMock() + slot.report.return_value = {"jev_input_tokens": 0, "decisions": 1} + slot.ticks = [] + final = json.dumps({"status": "DONE", "answer": "Fixture answer"}) + with ( + mock.patch.object(browse, "CountingModel") as counting, + mock.patch.object(browse, "BrowserDecisionModel", return_value=slot) as slot_class, + mock.patch.object(browse, "create_browser_agent") as create_agent, + mock.patch.object( + browse, + "run_task", + new=mock.AsyncMock(return_value={"ok": True, "final": final, "error": None}), + ) as run_task, + mock.patch.object(browse, "usage_summary", return_value={"decisions": 1}), + ): + with tempfile.TemporaryDirectory() as directory: + answer = await browse.browse( + spec(), + BrowserPolicy(prefetch_values=False, batch_actions=False, goal_value_cache=False), + model_name="clef", + goal="Open the fixture", + timeout_s=10, + max_steps=2, + logs_dir=Path(directory), + headless=True, + chat=mock.MagicMock(), + decision_model=decision_model, + ) + self.assertTrue((Path(directory) / "decision_ticks.json").is_file()) + self.assertIs(slot_class.call_args.args[2], counting.return_value) + self.assertIs(slot_class.call_args.kwargs["decision_model"], decision_model) + self.assertEqual(slot_class.call_args.kwargs["max_steps"], 2) + self.assertIs(create_agent.call_args.args[0], slot) + run_task.assert_awaited_once() + self.assertEqual(answer["final"], "Fixture answer") + + +class TestSeriesSharesTheModel(TestCase): + def test_series_treats_clef_as_a_shared_decision_model(self) -> None: + source = Path(series.__file__).read_text(encoding="utf-8") + self.assertIn('("jev", "clm", "laya", "laya-served", "cua", "clef")', source) diff --git a/tests/test_decision_models_clef.py b/tests/test_decision_models_clef.py new file mode 100644 index 0000000..8c5a7d4 --- /dev/null +++ b/tests/test_decision_models_clef.py @@ -0,0 +1,476 @@ +# coding: utf-8 +"""``clef`` served client: contract tests against a fake HTTP server (no Cloudflare / GPU).""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import os +from typing import Any +from unittest import IsolatedAsyncioTestCase, TestCase +from unittest.mock import patch + +import httpx +from openjiuwen.core.common.exception.codes import StatusCode +from openjiuwen.core.common.exception.errors import BaseError + +import decision_model_contract as contract +from s1a.decision_models import ChoiceQuestion, DecisionModel, Image, Observation, build_model +from s1a.decision_models.clef import ( + DEFAULT_CLEF_MODEL, + ClefClient, + ClefModel, + clef_image, + clef_images, + clef_payload, + clef_question, + workers_ai_url, +) + +SCREEN = Image(b"\x89PNG\r\n\x1a\n" + b"\x00" * 24, media_type="image/png") +URL = "http://clef.test" +ACCOUNT = "acct-test" +WORKERS = workers_ai_url(ACCOUNT, DEFAULT_CLEF_MODEL) + + +def _choice_answer(question: dict[str, Any]) -> dict[str, Any]: + keys = list(question["criteria"]) + if not keys: + return {"type": "choice", "choice": "", "probabilities": {}, "confidence": 0.0} + if len(keys) == 1: + probabilities = {keys[0]: 1.0} + else: + rest = 0.2 / (len(keys) - 1) + probabilities = {key: (0.8 if i == 0 else rest) for i, key in enumerate(keys)} + return {"type": "choice", "choice": keys[0], "probabilities": probabilities, "confidence": probabilities[keys[0]]} + + +def _noul_answer(_question: dict[str, Any]) -> dict[str, Any]: + return {"type": "noul", "noul": 0.65} + + +def _decision_body(request: httpx.Request) -> dict[str, Any]: + body = json.loads(request.content) + answers = {} + for name, question in body["questions"].items(): + answers[name] = _noul_answer(question) if question["type"] == "noul" else _choice_answer(question) + return { + "model": body.get("model") or DEFAULT_CLEF_MODEL, + "answers": answers, + "usage": {"input_tokens": 12, "output_tokens": 0}, + } + + +class Server: + """Scripted local ``/v1/systemone`` + ``/health``, or a Workers AI run endpoint.""" + + def __init__( + self, + *, + health: Any = None, + script: list[Any] | None = None, + envelope: bool = False, + ) -> None: + self.health = health if health is not None else {"model": DEFAULT_CLEF_MODEL, "device": "cuda"} + self.script = list(script or []) + self.envelope = envelope + self.decisions: list[httpx.Request] = [] + self.health_calls = 0 + + def answer(self, request: httpx.Request) -> httpx.Response: + payload = _decision_body(request) + if self.envelope: + return httpx.Response(200, json={"success": True, "result": payload, "errors": [], "messages": []}) + return httpx.Response(200, json=payload) + + def handler(self, request: httpx.Request) -> httpx.Response: + if request.url.path == "/health": + self.health_calls += 1 + if isinstance(self.health, Exception): + raise self.health + if isinstance(self.health, httpx.Response): + return self.health + return httpx.Response(200, json=self.health) + self.decisions.append(request) + if self.script: + step = self.script.pop(0) + if isinstance(step, Exception): + raise step + if callable(step): + return step(request) + return step + return self.answer(request) + + +def make_local(server: Server, *, timeout_s: float = 5.0, model: str = DEFAULT_CLEF_MODEL) -> ClefModel: + client = ClefClient( + url=URL + "/", + endpoint=URL + "/v1/systemone", + timeout_s=timeout_s, + transport=httpx.MockTransport(server.handler), + health_url=URL + "/health", + path="local", + ) + return ClefModel(client, model=model) + + +def make_workers(server: Server, *, timeout_s: float = 5.0, model: str = DEFAULT_CLEF_MODEL) -> ClefModel: + client = ClefClient( + url=WORKERS, + endpoint=WORKERS, + api_key="token", + timeout_s=timeout_s, + transport=httpx.MockTransport(server.handler), + path="workers-ai", + ) + return ClefModel(client, model=model) + + +class TestClefContract(contract.DecisionModelContract, IsolatedAsyncioTestCase): + def make(self) -> DecisionModel: + return make_local(Server()) + + def make_scripted(self, answers: list[dict[str, Any]]) -> DecisionModel: + script = [ + httpx.Response(200, json={"model": DEFAULT_CLEF_MODEL, "answers": a, "usage": {"input_tokens": 8}}) + for a in answers + ] + return make_local(Server(script=script)) + + +class TestRequestBody(IsolatedAsyncioTestCase): + async def test_text_path_omits_images_and_posts_systemone(self) -> None: + server = Server() + await make_local(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK, "check": contract.CHECK}) + request = server.decisions[0] + self.assertEqual(request.url, httpx.URL(URL + "/v1/systemone")) + body = json.loads(request.content) + self.assertEqual(body["model"], DEFAULT_CLEF_MODEL) + self.assertEqual(body["state"], contract.OBSERVATION.state) + self.assertNotIn("images", body) + self.assertNotIn("media", body) + self.assertNotIn("videos", body) + self.assertEqual(body["questions"]["pick"]["type"], "choice") + self.assertEqual(body["questions"]["check"]["type"], "noul") + self.assertIsInstance(body["questions"]["pick"]["instructions"], str) + self.assertIn("X-Request-Id", request.headers) + + async def test_images_are_clef_data_urls_not_onejev_media(self) -> None: + server = Server() + pictured = Observation({"task": "Pay the invoice"}, images=(SCREEN,)) + await make_local(server).decide_many(pictured, {"pick": contract.PICK}) + body = json.loads(server.decisions[0].content) + self.assertNotIn("media", body) + self.assertEqual(len(body["images"]), 1) + self.assertTrue(body["images"][0].startswith("data:image/png;base64,")) + decoded = base64.b64decode(body["images"][0].split(",", 1)[1]) + self.assertEqual(decoded, SCREEN.data) + self.assertEqual(body["state"], {"task": "Pay the invoice"}) + + async def test_provenance_fields_and_no_image_bytes_in_raw(self) -> None: + pictured = Observation({"task": "Pay the invoice"}, images=(SCREEN,)) + decision = await make_local(Server()).decide_many(pictured, {"pick": contract.PICK}) + self.assertEqual(decision.raw["url"], URL) + self.assertIsInstance(decision.raw["request_id"], str) + self.assertEqual(decision.raw["served_by"]["path"], "local") + self.assertEqual(decision.raw["served_by"]["checkpoint"], DEFAULT_CLEF_MODEL) + self.assertEqual(decision.raw["sent_images"][0]["bytes"], len(SCREEN.data)) + dumped = json.dumps(decision.raw) + self.assertNotIn(base64.b64encode(SCREEN.data).decode("ascii"), dumped) + + async def test_workers_ai_unwraps_the_rest_envelope(self) -> None: + server = Server(envelope=True) + decision = await make_workers(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK}) + request = server.decisions[0] + self.assertEqual(str(request.url), WORKERS) + self.assertTrue(request.headers["Authorization"].startswith("Bearer ")) + self.assertEqual(decision.choice("pick").key, "hit") + self.assertEqual(decision.model, DEFAULT_CLEF_MODEL) + self.assertEqual(decision.raw["served_by"]["path"], "workers-ai") + self.assertEqual(decision.usage.input_tokens, 12) + self.assertEqual(server.health_calls, 0) + + async def test_workers_ai_records_cf_ray(self) -> None: + def with_ray(request: httpx.Request) -> httpx.Response: + payload = _decision_body(request) + return httpx.Response( + 200, + json={"success": True, "result": payload, "errors": [], "messages": []}, + headers={"cf-ray": "abc-DFW"}, + ) + + decision = await make_workers(Server(script=[with_ray])).decide_many( + contract.OBSERVATION, {"pick": contract.PICK} + ) + self.assertEqual(decision.raw["cf_ray"], "abc-DFW") + + async def test_browser_element_row_becomes_label(self) -> None: + server = Server() + question = ChoiceQuestion( + {"12": {"element": "[12] Where from?", "current_value": "Zurich", "role": "combobox"}}, + goal="book a flight", + ) + await make_local(server).decide_many(contract.OBSERVATION, {"click_target": question}) + asked = json.loads(server.decisions[0].content)["questions"]["click_target"] + self.assertEqual(asked["criteria"], {"12": "Where from? = Zurich"}) + self.assertIn("book a flight", asked["instructions"]) + + +class TestFailures(IsolatedAsyncioTestCase): + async def test_too_many_images_is_a_call_failure(self) -> None: + pictured = Observation("x", images=tuple(SCREEN for _ in range(5))) + with self.assertRaises(BaseError) as caught: + await make_local(Server()).decide_many(pictured, {"pick": contract.PICK}) + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("at most 4", str(caught.exception)) + + async def test_transport_error_is_a_call_failure(self) -> None: + server = Server(script=[httpx.ConnectError("refused"), httpx.ConnectError("refused")]) + with self.assertRaises(BaseError) as caught: + await make_local(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK}) + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("clef", str(caught.exception).lower()) + + async def test_malformed_answers_object_is_a_call_failure(self) -> None: + server = Server(script=[httpx.Response(200, json={"model": "x", "answers": "nope"})]) + with self.assertRaises(BaseError) as caught: + await make_local(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK}) + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("answers", str(caught.exception).lower()) + + async def test_workers_ai_error_envelope_is_a_call_failure(self) -> None: + server = Server( + script=[ + httpx.Response( + 200, json={"success": False, "errors": [{"code": 10000, "message": "nope"}], "result": None} + ) + ] + ) + with self.assertRaises(BaseError) as caught: + await make_workers(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK}) + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("nope", str(caught.exception)) + + async def test_http_error_is_a_call_failure(self) -> None: + server = Server(script=[httpx.Response(500, text="boom")]) + with self.assertRaises(BaseError) as caught: + await make_local(server).decide_many(contract.OBSERVATION, {"pick": contract.PICK}) + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("500", str(caught.exception)) + + +class TestDecisionDeadline(IsolatedAsyncioTestCase): + async def test_retry_uses_remaining_budget_for_httpx_and_wait_for(self) -> None: + for failure in (httpx.ConnectError("refused"), httpx.Response(502), httpx.Response(504)): + with self.subTest(failure=failure): + now = 0.0 + requests = [] + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal now + requests.append(request) + if len(requests) == 1: + now += 1.25 + if isinstance(failure, Exception): + raise failure + return failure + return httpx.Response(200, json={"answers": {}}) + + client = ClefClient( + url=URL, + endpoint=URL + "/v1/systemone", + timeout_s=2.0, + transport=httpx.MockTransport(handler), + clock=lambda: now, + path="local", + ) + self.addAsyncCleanup(client.close) + with patch("s1a.decision_models.clef.asyncio.wait_for", wraps=asyncio.wait_for) as wait_for: + await client.decide({"questions": {}}, "same-request") + self.assertEqual([call.args[1] for call in wait_for.call_args_list], [2.0, 0.75]) + for request, timeout in zip(requests, (2.0, 0.75), strict=True): + self.assertEqual(set(request.extensions["timeout"].values()), {timeout}) + self.assertEqual(request.headers["X-Request-Id"], "same-request") + + async def test_exhausted_budget_prevents_retry(self) -> None: + for failure in (httpx.ConnectError("refused"), httpx.Response(502), httpx.Response(504)): + with self.subTest(failure=failure): + now = 0.0 + requests = [] + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal now + requests.append(request) + now += 2.0 + if isinstance(failure, Exception): + raise failure + return failure + + client = ClefClient( + url=URL, + endpoint=URL + "/v1/systemone", + timeout_s=2.0, + transport=httpx.MockTransport(handler), + clock=lambda: now, + path="local", + ) + self.addAsyncCleanup(client.close) + with self.assertRaises(BaseError) as caught: + await client.decide({"questions": {}}, "exhausted") + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIn("within 2 s", str(caught.exception)) + self.assertEqual(len(requests), 1) + + async def test_stalled_retry_is_cancelled_at_remaining_deadline(self) -> None: + now = 0.0 + attempts = 0 + stopped = asyncio.Event() + + async def handler(request: httpx.Request) -> httpx.Response: + nonlocal now, attempts + attempts += 1 + if attempts == 1: + now = 0.99 + raise httpx.ConnectError("refused", request=request) + try: + await asyncio.Event().wait() + finally: + stopped.set() + raise AssertionError("stalled retry was not cancelled") + + client = ClefClient( + url=URL, + endpoint=URL + "/v1/systemone", + timeout_s=1.0, + transport=httpx.MockTransport(handler), + clock=lambda: now, + path="local", + ) + self.addAsyncCleanup(client.close) + with patch("s1a.decision_models.clef.asyncio.wait_for", wraps=asyncio.wait_for) as wait_for: + with self.assertRaises(BaseError) as caught: + await client.decide({"questions": {}}, "stalled") + self.assertEqual(caught.exception.status, StatusCode.MODEL_CALL_FAILED) + self.assertIsInstance(caught.exception.__cause__, TimeoutError) + self.assertAlmostEqual(wait_for.call_args_list[1].args[1], 0.01) + self.assertEqual(attempts, 2) + self.assertTrue(stopped.is_set()) + + +class TestMappingHelpers(TestCase): + def test_payload_unwraps_workers_ai_envelope_and_rejects_bad_bodies(self) -> None: + inner = { + "model": "clef-flash", + "answers": {"pick": {"noul": 0.2}}, + "usage": {"input_tokens": 1, "output_tokens": 0}, + } + self.assertEqual(clef_payload(inner), inner) + self.assertEqual(clef_payload({"success": True, "result": inner}), inner) + with self.assertRaises(BaseError): + clef_payload({"success": False, "errors": [{"message": "denied"}], "result": None}) + with self.assertRaises(BaseError): + clef_payload({"result": {"nope": True}}) + + def test_image_rejects_empty_and_unknown_types(self) -> None: + with self.assertRaises(BaseError): + clef_image(Image(b"", media_type="image/png")) + with self.assertRaises(BaseError): + clef_image(Image(b"x", media_type="image/gif")) + with self.assertRaises(BaseError): + clef_images((SCREEN,) * 5) + + def test_question_uses_string_instructions(self) -> None: + asked = clef_question(ChoiceQuestion({"a": "A"}, goal="g", rules="r")) + self.assertEqual(asked["type"], "choice") + self.assertIsInstance(asked["instructions"], str) + self.assertIn("g", asked["instructions"]) + self.assertEqual(asked["criteria"], {"a": "A"}) + + def test_workers_ai_url_matches_the_official_path(self) -> None: + self.assertEqual( + workers_ai_url("abc", "clef"), + "https://api.cloudflare.com/client/v4/accounts/abc/ai/run/@cf/cloudflare/clef", + ) + self.assertEqual( + workers_ai_url("abc", "clef-flash"), + "https://api.cloudflare.com/client/v4/accounts/abc/ai/run/@cf/cloudflare/clef-flash", + ) + + +class TestFromEnv(TestCase): + def test_missing_url_and_token_is_a_config_error(self) -> None: + with patch.dict( + os.environ, + {"CLEF_URL": "", "CLOUDFLARE_ACCOUNT_ID": "", "CLOUDFLARE_AUTH_TOKEN": "", "CLOUDFLARE_API_TOKEN": ""}, + clear=False, + ): + os.environ.pop("CLEF_URL", None) + os.environ.pop("CLOUDFLARE_ACCOUNT_ID", None) + os.environ.pop("CLOUDFLARE_AUTH_TOKEN", None) + os.environ.pop("CLOUDFLARE_API_TOKEN", None) + with self.assertRaises(BaseError) as caught: + ClefModel.from_env() + self.assertEqual(caught.exception.status, StatusCode.MODEL_SERVICE_CONFIG_ERROR) + self.assertIn("CLEF_URL", str(caught.exception)) + self.assertIn("CLOUDFLARE_ACCOUNT_ID", str(caught.exception)) + + def test_build_model_clef_from_local_url(self) -> None: + with patch.dict(os.environ, {"CLEF_URL": "http://127.0.0.1:30000", "CLEF_MODEL": "clef"}): + model = build_model("clef") + self.assertIsInstance(model, ClefModel) + self.assertEqual(model.name, "clef") + self.assertEqual(model.model, "clef") + self.assertTrue(model.supports_images) + self.assertEqual(model._client.path, "local") + self.assertEqual(model._client.endpoint, "http://127.0.0.1:30000/v1/systemone") + + def test_build_model_clef_from_workers_ai_env(self) -> None: + env = { + "CLEF_URL": "", + "CLOUDFLARE_ACCOUNT_ID": ACCOUNT, + "CLOUDFLARE_AUTH_TOKEN": "secret", + "CLEF_MODEL": "clef-flash", + } + with patch.dict(os.environ, env, clear=False): + os.environ.pop("CLEF_URL", None) + model = build_model("clef") + self.assertIsInstance(model, ClefModel) + self.assertEqual(model.model, DEFAULT_CLEF_MODEL) + self.assertEqual(model._client.path, "workers-ai") + self.assertEqual(model._client.endpoint, WORKERS) + self.assertIsNone(model._client.health_url) + + def test_local_url_wins_over_cloudflare_credentials(self) -> None: + with patch.dict( + os.environ, + { + "CLEF_URL": "http://127.0.0.1:30000", + "CLOUDFLARE_ACCOUNT_ID": ACCOUNT, + "CLOUDFLARE_AUTH_TOKEN": "secret", + }, + ): + model = ClefModel.from_env() + self.assertEqual(model._client.path, "local") + + def test_api_token_alias_is_accepted(self) -> None: + with patch.dict( + os.environ, + {"CLOUDFLARE_ACCOUNT_ID": ACCOUNT, "CLOUDFLARE_API_TOKEN": "alias", "CLOUDFLARE_AUTH_TOKEN": ""}, + clear=False, + ): + os.environ.pop("CLEF_URL", None) + os.environ.pop("CLOUDFLARE_AUTH_TOKEN", None) + model = ClefModel.from_env() + self.assertEqual(model._client.path, "workers-ai") + + def test_bad_model_and_timeout_are_config_errors(self) -> None: + with patch.dict(os.environ, {"CLEF_URL": "http://127.0.0.1:30000", "CLEF_MODEL": "clef-omni"}): + with self.assertRaises(BaseError) as caught: + ClefModel.from_env() + self.assertEqual(caught.exception.status, StatusCode.MODEL_SERVICE_CONFIG_ERROR) + self.assertIn("clef-flash", str(caught.exception)) + with patch.dict(os.environ, {"CLEF_URL": "http://127.0.0.1:30000", "CLEF_TIMEOUT_S": "0"}): + with self.assertRaises(BaseError) as caught: + ClefModel.from_env() + self.assertEqual(caught.exception.status, StatusCode.MODEL_SERVICE_CONFIG_ERROR) diff --git a/tests/test_decision_models_factory.py b/tests/test_decision_models_factory.py index cc51ab6..980e128 100644 --- a/tests/test_decision_models_factory.py +++ b/tests/test_decision_models_factory.py @@ -46,7 +46,19 @@ def test_every_name_builds_its_class(self) -> None: self.assertEqual(rule.name, "always-inc") self.assertEqual( DECISION_MODEL_NAMES, - ("jev", "jev-vl-served", "clm", "laya", "laya-served", "cua", "omnijev", "onejev", "random", "rule"), + ( + "jev", + "jev-vl-served", + "clm", + "laya", + "laya-served", + "cua", + "omnijev", + "onejev", + "clef", + "random", + "rule", + ), ) def test_the_errors(self) -> None: diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 024e29a..b034e88 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -162,7 +162,7 @@ async def test_decide_advertises_optional_model_choices(self) -> None: async with create_connected_server_and_client_session(mcp_server.server) as session: tools = await session.list_tools() schema = next(tool.inputSchema for tool in tools.tools if tool.name == "decide") - self.assertEqual(schema["properties"]["model"]["enum"], ["jev", "clm", "laya", "laya-served", "cua"]) + self.assertEqual(schema["properties"]["model"]["enum"], ["jev", "clm", "laya", "laya-served", "cua", "clef"]) self.assertEqual(schema["properties"]["model"]["default"], "jev") self.assertNotIn("model", schema["required"]) @@ -259,7 +259,7 @@ async def test_list_agents_names_every_front_with_its_flags(self) -> None: flags = {name: {row["flag"]: row for row in rows[name]["flags"]} for name in ("game2048", "flights")} self.assertEqual( (flags["game2048"]["--model"]["required"], flags["game2048"]["--model"]["choices"]), - (True, ["jev", "clm", "llm", "random", "rule", "laya", "laya-served", "cua"]), + (True, ["jev", "clm", "llm", "random", "rule", "laya", "laya-served", "cua", "clef"]), ) max_steps = str(agents.load("game2048").budget.max_steps) self.assertEqual(