Skip to content
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,28 @@

All notable changes to this project will be documented in this file.

## Unreleased

### Added

- Evaluate a model on a dataset version of the same project.
`Workspace.create_model_evaluation(model, project, version=None)` starts the eval
and returns `{evalId, status, reused, version, trainedOnVersion, leakage, classMismatch}`.
`Workspace.check_model_evaluation_compatibility(...)` returns `{allowed, blocks, ...}` and starts no job.
`rerun=True` (CLI: `--rerun`) starts a new eval when a done eval exists.
A pending or running eval still returns with `reused: true`.
Leakage and class mismatch never block an eval. They are tags on the result.
A tag is `None` when the platform has no value for it, for example for the training version.
A blocked request raises `ModelEvalBlockedError` with a `blocks` list.
`ModelEvalNotFoundError` and `ModelEvalAccessError` now cover these requests too.
A full workspace raises `ModelEvalConcurrencyLimitError`.
The CLI is `roboflow eval create` and `roboflow eval check-compatibility`
(`-m <model> -p <project> [-v <version>]`).
Exit code 6 means blocked. Exit code 7 means the concurrency limit.
`Workspace.eval` and `roboflow eval get --json` keep the same three tags.
Needs the `POST /{workspace}/model-evals` and `POST /{workspace}/model-evals/check-compatibility` APIs
([#591](https://github.com/roboflow/roboflow-python/pull/591)).

## 1.7.5

### Added
Expand Down
22 changes: 22 additions & 0 deletions CLI-COMMANDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,28 @@ without parsing message strings: `2` for authentication or access errors (401/40
`invalid_split` / `invalid_confidence` (400). Requires the
`model-eval:read` scope on the api key.

### Evaluate a model on another dataset version

```bash
# Check the request first. This starts no job.
roboflow eval check-compatibility -m my-workspace/my-model -p my-project -v 5 --json

# Start the eval. Omit -v to use the version the model trained on.
roboflow eval create -m my-workspace/my-model -p my-project -v 5 --json
```

Both commands return `trainedOnVersion`, `leakage` and `classMismatch`.
Leakage and class mismatch never block an eval. The eval runs with these tags.
A tag is `null` when the platform has no value for it, for example for the training version.
Text output omits a null tag.
`create` returns `reused: true` when an eval for the same model, version and
settings is pending, running or done. Add `--rerun` to start a new eval when a
done eval exists. A pending or running eval still returns `reused: true`.
Exit code `6` means a compatibility block. The error message lists each block.
Run `eval check-compatibility --json` for the structured `blocks` list.
Exit code `7` means the workspace has too many active evals.
Requires the `training-job:create` scope and workspace Model Evaluation access.

### Compare Models

```bash
Expand Down
111 changes: 102 additions & 9 deletions roboflow/adapters/rfapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2309,15 +2309,30 @@ def restore_trash_item(api_key, workspace_url, item_type, item_id, parent_id=Non


class ModelEvalNotFoundError(RoboflowError):
"""Raised when an eval id (or workspace) does not exist (HTTP 404)."""
"""Raised when an eval id, workspace, model, project or version does not exist (HTTP 404)."""


class ModelEvalNotDoneError(RoboflowError):
"""Raised when reading panel data for an eval whose status is not ``done`` (HTTP 409)."""


class ModelEvalAccessError(RoboflowError):
"""Raised when an evaluation read is not authorized (HTTP 401 or 403)."""
"""Raised when an evaluation request is not authorized (HTTP 401 or 403)."""


class ModelEvalBlockedError(RoboflowError):
"""Raised when a compatibility check blocks the eval (HTTP 409 with ``blocks``).

``blocks`` is the server list of ``{"code": ..., "message": ...}`` dicts.
"""

def __init__(self, message, blocks, status_code=409):
super().__init__(message, status_code=status_code)
self.blocks = blocks


class ModelEvalConcurrencyLimitError(RoboflowError):
"""Raised when the workspace has too many active evals (HTTP 429, ``eval_concurrency_limit``)."""


class InvalidSplitError(RoboflowError):
Expand All @@ -2328,27 +2343,40 @@ class InvalidConfidenceError(RoboflowError):
"""Raised when ``confidence`` is non-integer or out of range 0-100 (HTTP 400)."""


def _model_eval_error_for(response):
def _model_eval_error_for(response, start=False):
"""Translate a model-eval error response into the right RoboflowError subclass.

The model-eval REST surface returns errors as a flat envelope::
The read routes return a flat envelope::

{"error": "<code>", "message": "<human readable>"}

The create and compatibility check calls (``start=True``) also return
``{"error": "<message>", "code": "<code>", "details": {"blocks": [...]}}`` for a blocked start
and ``{"error": {"code": "<code>", "message": "<message>"}}`` for the concurrency limit.

Falls back to plain :class:`RoboflowError` when the body isn't JSON or
the code is unrecognised, so new error codes don't crash older SDK
callers. Status-code fallbacks for 404/409 keep typed exceptions
available even if the server omits the ``error`` field.
available even if the server omits the code.
"""
code = None
message = response.text
blocks = None
try:
body = response.json()
if isinstance(body, dict):
code = body.get("error")
if not isinstance(code, str):
code = None
message = body.get("message") or code or message
error = body.get("error")
if start and isinstance(error, dict):
code, text = error.get("code"), error.get("message")
elif start and "code" in body:
code, text = body["code"], error
else:
code, text = error, body.get("message")
code = code if isinstance(code, str) else None
message = text if isinstance(text, str) and text else code or message
details = body.get("details")
if start and isinstance(details, dict) and isinstance(details.get("blocks"), list):
blocks = details["blocks"]
except (ValueError, TypeError):
pass

Expand All @@ -2361,6 +2389,14 @@ def _model_eval_error_for(response):
cls = cls_by_code.get(code or "")
if response.status_code in (401, 403):
return ModelEvalAccessError(message)
if response.status_code == 409 and blocks:
return ModelEvalBlockedError(
"\n".join(f"{block.get('code')}: {block.get('message')}" for block in blocks),
blocks,
status_code=409,
)
if response.status_code == 429 and code == "eval_concurrency_limit":
return ModelEvalConcurrencyLimitError(message, status_code=429)
if cls is not None:
return cls(message)
if response.status_code == 404:
Expand All @@ -2384,6 +2420,63 @@ def _eval_get(api_key, workspace_url, path, params=None):
return response.json()


def _eval_post(api_key, workspace_url, path, body):
"""POST helper for model-eval endpoints with typed error mapping."""
url = f"{API_URL}/{workspace_url}/model-evals{path}"
response = http.post(url, params={"api_key": api_key}, json=body)
if response.status_code != 200:
raise _model_eval_error_for(response, start=True)
return response.json()


def _eval_start_body(model, project, version):
body: Dict[str, Any] = {"modelId": model, "project": project}
if version is not None:
body["version"] = str(version)
return body


def create_model_eval(
api_key: str,
workspace_url: str,
*,
model: str,
project: str,
version: Optional[Union[str, int]] = None,
rerun: bool = False,
) -> dict:
"""POST /{workspace}/model-evals — evaluate a model on a dataset version of its project.

``model`` is ``{workspace}/{model}`` or the bare model slug. ``version`` defaults to the
version the model trained on. The call is idempotent: an eval that is pending, running or done
for the same model, version and settings comes back with ``reused: true``. With ``rerun=True``
a done eval does not count, so a new eval starts. A pending or running eval still comes back
with ``reused: true``.

Raises :class:`ModelEvalBlockedError` (409), :class:`ModelEvalConcurrencyLimitError` (429),
:class:`ModelEvalNotFoundError` (404) and :class:`ModelEvalAccessError` (401 or 403).
"""
body = _eval_start_body(model, project, version)
if rerun:
body["rerun"] = True
return _eval_post(api_key, workspace_url, "", body)


def check_model_eval_compatibility(
api_key: str,
workspace_url: str,
*,
model: str,
project: str,
version: Optional[Union[str, int]] = None,
) -> dict:
"""POST /{workspace}/model-evals/check-compatibility — check an eval request without starting it.

A blocked request is a normal result (``allowed: false`` with ``blocks``), not an error.
"""
return _eval_post(api_key, workspace_url, "/check-compatibility", _eval_start_body(model, project, version))


def compare_model_evals(
api_key: str,
workspace_url: str,
Expand Down
128 changes: 124 additions & 4 deletions roboflow/cli/handlers/eval.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Model evaluation commands.

Wraps the public ``/{workspace}/model-evals`` REST surface — list runs in a
workspace and pull each panel (mAP, confidence sweep, per-class table,
Wraps the public ``/{workspace}/model-evals`` REST surface — start a run,
check a request, list runs in a workspace and pull each panel (mAP, confidence sweep, per-class table,
confusion matrix, vector clusters, per-image stats, recommendations).

The eval-id is opaque (the human in the UI navigates by URL); commands take
Expand All @@ -16,14 +16,51 @@

from roboflow.cli._compat import SortedGroup, ctx_to_args

eval_app = typer.Typer(cls=SortedGroup, help="Inspect model evaluation runs", no_args_is_help=True)
eval_app = typer.Typer(cls=SortedGroup, help="Create and inspect model evaluation runs", no_args_is_help=True)


# ---------------------------------------------------------------------------
# Command surface (Typer)
# ---------------------------------------------------------------------------


@eval_app.command("create")
def create_eval_cmd(
ctx: typer.Context,
model: Annotated[str, typer.Option("-m", "--model", help="Model URL (workspace/model) or model slug")],
project: Annotated[str, typer.Option("-p", "--project", help="Project slug")],
version: Annotated[
Optional[int],
typer.Option(
"-v", "--version", min=1, help="Dataset version number (default: the version the model trained on)"
),
] = None,
rerun: Annotated[
bool, typer.Option("--rerun", help="Start a new eval even when a done eval exists for the request")
] = False,
) -> None:
"""Evaluate a model on a dataset version of its project."""
args = ctx_to_args(ctx, model=model, project=project, version=version, rerun=rerun)
_create_eval(args)


@eval_app.command("check-compatibility")
def check_compatibility_eval_cmd(
ctx: typer.Context,
model: Annotated[str, typer.Option("-m", "--model", help="Model URL (workspace/model) or model slug")],
project: Annotated[str, typer.Option("-p", "--project", help="Project slug")],
version: Annotated[
Optional[int],
typer.Option(
"-v", "--version", min=1, help="Dataset version number (default: the version the model trained on)"
),
] = None,
) -> None:
"""Check an evaluation request without starting it."""
args = ctx_to_args(ctx, model=model, project=project, version=version)
_check_compatibility_eval(args)


@eval_app.command("compare")
def compare_evals_cmd(
ctx: typer.Context,
Expand Down Expand Up @@ -183,7 +220,8 @@ def _eval_error_exit_code(exc: Exception) -> int:
"""Map a model-eval error to the canonical CLI exit code.

1 = general; 2 = auth; 3 = not found; 4 = conflict (eval not done);
5 = invalid argument (bad split / confidence). Keeping these distinct
5 = invalid argument (bad split / confidence); 6 = eval blocked by a
compatibility check; 7 = workspace eval concurrency limit. Keeping these distinct
lets shell scripts and AI agents react to specific failure modes
without parsing message strings.
"""
Expand All @@ -197,6 +235,10 @@ def _eval_error_exit_code(exc: Exception) -> int:
return 4
if isinstance(exc, (rfapi.InvalidSplitError, rfapi.InvalidConfidenceError)):
return 5
if isinstance(exc, rfapi.ModelEvalBlockedError):
return 6
if isinstance(exc, rfapi.ModelEvalConcurrencyLimitError):
return 7
return 1


Expand All @@ -217,6 +259,84 @@ def _hint_for(exc: Exception) -> Optional[str]:
return None


def _start_hint_for(exc: Exception) -> Optional[str]:
"""Hint for the start commands. A blocked error has none: its message lists the blocks."""
from roboflow.adapters import rfapi

if isinstance(exc, rfapi.ModelEvalAccessError):
return "Check your API key, its training-job:create scope, and workspace Model Evaluation access."
if isinstance(exc, rfapi.ModelEvalNotFoundError):
return (
"Check the --model, --project and --version values, and that the API key has the training-job:create scope."
)
if isinstance(exc, rfapi.ModelEvalConcurrencyLimitError):
return "Wait for an active eval to finish, then try again."
return None


def _format_tags(result) -> list: # noqa: ANN001
"""Text lines for the tags that are present: trained-on version, leakage and class mismatch."""
lines = []
if result.get("trainedOnVersion") is not None:
lines.append(f" Trained on version: {result['trainedOnVersion']}")
leakage = result.get("leakage")
if leakage is not None:
lines.append(f" Leakage: {leakage['status']}")
for split, counts in (leakage.get("splits") or {}).items():
lines.append(f" {split}: {counts['leaked']} of {counts['total']} images leaked")
mismatch = result.get("classMismatch")
if mismatch is not None:
lines.append(f" Classes only in the target version: {', '.join(mismatch['targetOnly']) or 'none'}")
lines.append(f" Classes only in the model: {', '.join(mismatch['modelOnly']) or 'none'}")
return lines


def _create_eval(args): # noqa: ANN001
from roboflow.adapters import rfapi
from roboflow.cli._output import output, output_error

resolved = _resolve(args)
if not resolved:
return
workspace_url, api_key = resolved
try:
result = rfapi.create_model_eval(
api_key, workspace_url, model=args.model, project=args.project, version=args.version, rerun=args.rerun
)
except Exception as exc:
output_error(args, str(exc), hint=_start_hint_for(exc), exit_code=_eval_error_exit_code(exc))
return
lines = [
f"Eval: {result['evalId']}",
f" Status: {result['status']}",
f" Reused: {'yes' if result['reused'] else 'no'}",
f" Version: {result['version']}",
*_format_tags(result),
]
output(args, result, text="\n".join(lines))


def _check_compatibility_eval(args): # noqa: ANN001
from roboflow.adapters import rfapi
from roboflow.cli._output import output, output_error

resolved = _resolve(args)
if not resolved:
return
workspace_url, api_key = resolved
try:
result = rfapi.check_model_eval_compatibility(
api_key, workspace_url, model=args.model, project=args.project, version=args.version
)
except Exception as exc:
output_error(args, str(exc), hint=_start_hint_for(exc), exit_code=_eval_error_exit_code(exc))
return
lines = [f"Allowed: {'yes' if result['allowed'] else 'no'}"]
lines.extend(f" Block {block['code']}: {block['message']}" for block in result["blocks"])
lines.extend(_format_tags(result))
output(args, result, text="\n".join(lines))


def _compare_evals(args): # noqa: ANN001
from roboflow.adapters import rfapi
from roboflow.cli._output import output, output_error
Expand Down
Loading
Loading