Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,78 @@ Unreleased changes live in [`changelog.d/`](changelog.d/README.md), one file per

## [Unreleased]

## [2.42.0] - 2026-12-03

### Added

- **Choose a music or 3D backend by the name its plugin registers** (`capabilities/registry.py`). A host
(`create_llm(..., music_backend=...)`, `capabilities_preferred_backends={...}`, `set_preferred_backend`) or a
request (`llm.music.generate(..., provider=...)` or its synonym `backend=`, `output={"modality": "music", ...}`,
`/v1/audio/music` and `/{provider}/v1/audio/music`, the scene3d equivalents) names a backend by its full id
(`abstractmusic:minimax-music3`) or its short name (`minimax-music3`), in any case or `_`/`-` spelling. A backend
a plugin registers is selectable at once, with no AbstractCore release.
- **A model named alone selects the backend that declares it.** `llm.music.generate(prompt, model=
"AbstractFramework/minimax-music3-8bit")`, a body `"model"` on `/v1/audio/music`, or a host's `music_model_id` runs
on the one registered backend that declares that model. Declared by several: the host's preference among them,
else refused naming them. Declared by none: the host's (or the configured route's) backend receives it only when
it runs any checkpoint, else refused naming the model.
- **One order of precedence**: what the request names, then what the host was constructed with, then the configured
`output.<modality>` route, then the highest priority. A configured route never replaces nor refuses a backend or a
model the request or the host names. A model named at the same level as its backend (request, host, or route) must
be one that backend runs, else the call is refused naming that level; a lower level's model goes only to a
backend that declares it.
- **`registry.declare_models(capability, backend_id, models, *, remote=None)` for plugin authors**: declare at
registration the models each backend runs (an empty list: it runs any checkpoint and is never selected by a model
alone). Routing by model builds no other backend and opens no connection. `registry.select(...)` returns the
backend and model a call would use; `registry.declared_models(...)` and `registry.selection_problem(...)` report.
- **A refusal contract** (`capabilities/backend_selectors.py`). A request refused as asked raises an error carrying
`request_refused = True`, `named_by` (`request`, `host` or `stored_route`) and `named_by_source`; read it with
`refusal_attributes(error)`. These errors survive pickling. The server answers 400 (409 when its own
configuration named the refused value) with `{"error": {"message", "type": "request_refused", "code",
"request_refused": true, "named_by", "named_by_source"}}`; a plugin's exception carrying the same attribute is
answered the same way.
- **What ran is reported.** A music result's `backend_id` is the backend AbstractCore selected, `model` the model
the backend reports it ran (the model it was handed is `metadata["requested_model"]`), and `metadata` the backend's
own report. `/v1/audio/music` adds `X-AbstractCore-Music-Backend`, `X-AbstractCore-Music-Model` and
`X-AbstractCore-Music-Metadata` headers (printable ASCII, capped; the body is unchanged).

### Changed

- **No music format is forced**: without `format`, the backend's own default applies and its MIME type is reported.
- **Discovery reports a preference or configured route that selects nothing** (`selection_error`,
`unused_preferences` in `status()`)
and keeps listing what is registered, including a second plugin's backends; only generation refuses.
- **The server reuses its capability backends** and follows its configuration while it runs: a changed or removed
route applies at once, without a restart, and a backend a request names is built once.
- **A host without a text model** (`create_capability_host()`, the server's capability core) offers plugins no text
service, so AbstractMusic plans music with its own planner instead of failing.

### Removed

- **Music configuration from the environment**: `ABSTRACTMUSIC_BACKEND`, `ABSTRACTMUSIC_MODEL_ID`,
`ABSTRACTMUSIC_DEVICE`, `ABSTRACTMUSIC_TORCH_DTYPE`, `ABSTRACTMUSIC_PIPELINE_CLASS`,
`ABSTRACTMUSIC_NUM_INFERENCE_STEPS`, `ABSTRACTMUSIC_DURATION_S`, `ABSTRACTMUSIC_GUIDANCE_SCALE`,
`ABSTRACTMUSIC_TEXT_PLANNER`, `ABSTRACTMUSIC_REVISION` and `ABSTRACTCORE_MUSIC_BACKEND` no longer configure the
server; a stray one is listed as `ignored_environment`. **Migration**: set `output.music` with
`abstractcore config`.

- **Static backend tables**: `music_selectors.MUSIC_BACKEND_IDS` / `MUSIC_BACKEND_NAMES`,
`scene3d_selectors.SCENE3D_BACKEND_IDS`, and the registry-free form of `resolve_music_backend_id` /
`resolve_scene3d_backend_id` (both now take `registered_ids=`). **Migration**: list registered backends with
`registry.list_backend_infos(capability)`.

### Fixed

- **A named backend, model or preference is used, or the call fails naming it**: an unknown, ambiguous, blank or
non-string name, a request selector in the query string, or an unread keyword (`backend_id`, `engine`) used to be
ignored and another backend, possibly a remote service, served. **Migration**: correct a preference or selector to
one of the registered names the error lists, or remove it to keep the highest-priority backend.
**Migration**: a host `music_model_id` naming a checkpoint no backend declares now needs a named backend
(`music_backend="acestep"`, `music_backend="diffusers"`). **Migration**: a request naming a backend this install
does not register is answered 400, not 501.
- **AbstractMusic floor**: `abstractmusic>=0.2.2` (model declarations, refusal attributes). **Migration**: upgrade
AbstractMusic with AbstractCore.

## [2.41.0] - 2026-11-29

### Changed
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
Unified LLM Interface
> Write once, run everywhere

What's new in 2.42.0: a music or 3D backend is chosen by the name its plugin registers (full id or short name), per host or per request, and a model named alone selects the backend that declares it, in one order of precedence: the request, then the host, then the configured route. A name that selects nothing is refused with the registered names, never replaced by another backend; refusals carry `request_refused` and who named the value, and the server answers them 400 or 409. Music results report the backend and model that ran. Music settings no longer come from `ABSTRACTMUSIC_*` environment variables. Requires `abstractmusic>=0.2.2`. See [CHANGELOG.md](CHANGELOG.md).

What's new in 2.41.0: the agent tools `execute_command` and `shell_exec` report a pipeline as failed when any of its commands fails (pipelines run with pipefail on macOS and Linux), so a build that fails behind `| grep` or `| head` is no longer reported as a success; `shell_exec` and `shell_write_stdin` return a dict with `success` and `rendered` instead of text (code that used the returned string reads `rendered`); on Linux a shell session is no longer closed when its timed-out command had already ended on its own; AbstractVision 0.3.39 is the oldest version installed (with the `apple` setting, MLX-Gen 0.40.4 or later). See [CHANGELOG.md](CHANGELOG.md#2410---2026-11-29).

What's new in 2.40.0: the server's vision routes take a memory mode (`default`, `low`, `lowest`), a load-time `quantize` and, for MiniMax-H3, soundtrack fields; discovery lists each model's memory modes, sound support and measured memory peaks; a running generation job can be cancelled; responses carry no filesystem paths and every error has an `error.code`. See [CHANGELOG.md](CHANGELOG.md#2400---2026-11-27).
Expand Down
286 changes: 286 additions & 0 deletions abstractcore/capabilities/backend_selectors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,286 @@
"""Resolve a backend selector against the backends that are actually registered.

One rule for every capability (voice, audio, vision, music, scene3d, camera)
and every place a backend can be named (a registry preference, a per-request
`provider=`, the server's `/v1/audio/music` selectors):

- a registered backend id selects itself (case and `_`/`-` spelling ignored);
- a short name (no `:`) selects the ONE registered backend whose id ends with
`:<name>` (`minimax-music3` -> `abstractmusic:minimax-music3`); two or more
such backends is an error that names them;
- a capability-specific alias (scene3d's `trellis2` -> `abstract3d:trellis2-local`)
selects its target only when that target is registered;
- anything else is an error that lists the registered backend ids.

Nothing here ever answers with a backend other than the one named, and no
static list decides what is accepted: a backend a plugin registers is
selectable by its id and its short name the moment it is registered.

A MODEL selects a backend against what the registered backends DECLARE at
registration (`CapabilityRegistry.declare_models`, `backends_declaring_model`):
model ids compare case-insensitively, and two backends declaring the same id
are an ambiguity.

Dependency-light on purpose (no registry import), so the server and the
config materializer can use it with whatever list of registered ids they hold.
"""

from __future__ import annotations

from typing import Any, Iterable, List, Mapping, Optional, Sequence

from .errors import PortableError


#: Who named a refused value (`named_by` of a selection refusal).
NAMED_BY_REQUEST = "request"
NAMED_BY_HOST = "host"
NAMED_BY_STORED_ROUTE = "stored_route"


class BackendSelectorError(PortableError, ValueError):
"""A selection refusal: the call names no registered backend, or more than one, or
names it in a form that is refused (a non-string or blank selector, two backends in
disagreement, an unknown capability key).

THE REFUSAL CONTRACT (for hosts and plugins): an exception that refuses the request
as asked carries `request_refused = True` (the caller must change the request: a
4xx, never retried), `named_by` (`"request"`, `"host"` or `"stored_route"`: who named
the refused value) and `named_by_source` (the argument or setting, when known:
`provider`, `music_backend`, `preferred_backends['music']`, `output.music route`).
A wrapper that re-raises it carries the same three attributes and keeps it as
`__cause__` (`refusal_attributes`). Plugins mark their own refusal classes with the
same attribute; AbstractCore reads the attribute, never a plugin's class names.

`registered` is every registered backend id for the capability (sorted);
`candidates` is non-empty only for an ambiguous name. `message` replaces the
default sentence for a refusal of the selector's form.
"""

request_refused = True

def __init__(
self,
*,
capability: str,
selector: str,
registered: Sequence[str] = (),
candidates: Sequence[str] = (),
message: Optional[str] = None,
named_by: Optional[str] = None,
named_by_source: Optional[str] = None,
) -> None:
self.capability = str(capability or "").strip() or "unknown"
self.selector = str(selector)
self.registered = sorted(str(b) for b in registered)
self.candidates = sorted(str(b) for b in candidates)
self.named_by = named_by
self.named_by_source = named_by_source
if message:
super().__init__(message)
return
if self.candidates:
message = (
f"{self.selector!r} matches more than one registered {self.capability} backend "
f"({', '.join(self.candidates)}); use the full backend id."
)
else:
message = f"{self.selector!r} is not a registered {self.capability} backend."
super().__init__(f"{message} {registered_backends_sentence(self.capability, self.registered)}")


def refusal_attributes(error: Optional[BaseException]) -> dict:
"""THE reader of the refusal contract: `{"request_refused": True, "named_by",
"named_by_source"}` of the first exception on `error`'s EXPLICIT cause chain
(`raise ... from ...`) whose `request_refused` is exactly `True`; {} when none is
a refusal. Hosts (the server, AbstractRuntime) read refusals with this, never by
class name."""

seen = set()
while error is not None and id(error) not in seen:
seen.add(id(error))
if getattr(error, "request_refused", False) is True:
return {
"request_refused": True,
"named_by": getattr(error, "named_by", None),
"named_by_source": getattr(error, "named_by_source", None),
}
error = error.__cause__
return {}


def selection_refusal(
capability: str,
message: str,
*,
named_by: str,
named_by_source: Optional[str] = None,
cause: Optional[BaseException] = None,
details: Optional[dict] = None,
) -> "CapabilityUnavailableError":
"""THE way AbstractCore raises a selection refusal (`raise selection_refusal(...)`): a
`CapabilityUnavailableError` carrying the refusal contract, whose `__cause__` is the
selector error stating it (`cause`, else a `BackendSelectorError` built from
`message`, `named_by` and `named_by_source`)."""

from .errors import CapabilityUnavailableError

if cause is None:
cause = BackendSelectorError(
capability=capability, selector="", message=message, named_by=named_by, named_by_source=named_by_source
)
error = CapabilityUnavailableError(capability=capability, reason=message, details=details)
error.__cause__ = cause
error.__suppress_context__ = True
error.request_refused = True
error.named_by = getattr(cause, "named_by", named_by)
error.named_by_source = getattr(cause, "named_by_source", named_by_source)
return error


def registered_backends_sentence(capability: str, registered: Iterable[str]) -> str:
"""`Registered music backends: a, b (short names: x, y).` or the no-backend sentence."""

ids = sorted(str(b) for b in registered)
if not ids:
return f"No {capability} backend is registered."
names = sorted({bid.rsplit(":", 1)[-1] for bid in ids if ":" in bid})
short = f" (short names: {', '.join(names)})" if names else ""
return f"Registered {capability} backends: {', '.join(ids)}{short}."


def normalize_backend_selector(value: Any) -> Optional[str]:
"""`" ABstractMusic:Stable_Audio "` -> `"abstractmusic:stable-audio"`; None when empty or not a string."""

if isinstance(value, str) and value.strip():
return value.strip().lower().replace("_", "-")
return None


def resolve_backend_selector(
capability: str,
selector: Any,
registered_ids: Iterable[str],
*,
aliases: Optional[Mapping[str, str]] = None,
named_by: Optional[str] = None,
named_by_source: Optional[str] = None,
) -> str:
"""The registered backend id `selector` names, or `BackendSelectorError` (carrying
`named_by` / `named_by_source`).

See the module docstring for the rule. `aliases` maps a normalized alias to
a full backend id; it is consulted only after the exact and short-name
matches, and its target must itself be registered.
"""

registered: List[str] = [str(b) for b in registered_ids if isinstance(b, str) and b.strip()]
raw = selector.strip() if isinstance(selector, str) else ""
if not raw:
raise BackendSelectorError(capability=capability, selector=str(selector), registered=registered, named_by=named_by, named_by_source=named_by_source)
if raw in registered:
return raw # an exact registered id always selects itself

# Every registered id the selector can name: the ids equal to it after
# normalization, and (for a name without ':') the ids whose name part equals
# it. More than one is an ambiguity, never "the first" (a bare registered id
# `Minimax_Music3` and `abstractmusic:minimax-music3` are both "minimax-music3").
text = normalize_backend_selector(raw) or ""
candidates = [bid for bid in registered if normalize_backend_selector(bid) == text]
if ":" not in text:
candidates += [
bid
for bid in registered
if ":" in bid
and (normalize_backend_selector(bid) or "").rsplit(":", 1)[-1] == text
and bid not in candidates
]
if len(candidates) == 1:
return candidates[0]
if len(candidates) > 1:
raise BackendSelectorError(capability=capability, selector=raw, registered=registered, candidates=candidates, named_by=named_by, named_by_source=named_by_source)

if aliases:
target = aliases.get(text)
if isinstance(target, str) and target in registered:
return target

raise BackendSelectorError(capability=capability, selector=raw, registered=registered, named_by=named_by, named_by_source=named_by_source)


class ModelSelectorError(PortableError, ValueError):
"""A selection refusal about a model: declared by no registered backend that could run
it, by more than one, or not runnable by the backend named (`message`). Same refusal
contract as `BackendSelectorError` (`request_refused`, `named_by`, `named_by_source`).

`declared` maps every backend that declared models to those models; `candidates` is
non-empty only when several backends declare the model.
"""

request_refused = True

def __init__(
self,
*,
capability: str,
model: str,
declared: Optional[Mapping[str, Sequence[str]]] = None,
candidates: Sequence[str] = (),
message: Optional[str] = None,
named_by: Optional[str] = None,
named_by_source: Optional[str] = None,
) -> None:
self.capability = str(capability or "").strip() or "unknown"
self.model = str(model)
self.declared = {str(b): sorted(str(m) for m in models) for b, models in sorted((declared or {}).items())}
self.candidates = sorted(str(b) for b in candidates)
self.named_by = named_by
self.named_by_source = named_by_source
if message:
super().__init__(message)
return
if self.candidates:
message = (
f"Model {self.model!r} is declared by more than one registered {self.capability} backend "
f"({', '.join(self.candidates)}); name the backend (provider=..., or the host's preferred "
f"{self.capability} backend)."
)
else:
message = f"No registered {self.capability} backend declares model {self.model!r}, and no other backend is used in its place."
listed = "; ".join(f"{b}: {', '.join(m) or '(any checkpoint)'}" for b, m in self.declared.items())
message += f" Declared models: {listed}." if listed else f" No registered {self.capability} backend declares any model."
message += " To run a checkpoint no backend declares, name a backend that runs any checkpoint (provider=...)."
super().__init__(message)


def normalize_model_id(value: Any) -> Optional[str]:
"""`" MiniMaxAI/MiniMax-Music3 "` -> `"minimaxai/minimax-music3"` (Hugging Face ids are
case-insensitive); None when empty or not a string."""

return value.strip().casefold() if isinstance(value, str) and value.strip() else None


def backends_declaring_model(model: Any, declared: Mapping[str, Iterable[str]]) -> List[str]:
"""The backend ids in `declared` ({backend_id: [model ids]}) that declare `model`
(compared case-insensitively), sorted. Empty for an empty `model`."""

wanted = normalize_model_id(model)
if not wanted:
return []
return sorted(b for b, models in declared.items() if any(normalize_model_id(m) == wanted for m in (models or ())))


__all__ = [
"NAMED_BY_HOST",
"NAMED_BY_REQUEST",
"NAMED_BY_STORED_ROUTE",
"refusal_attributes",
"selection_refusal",
"BackendSelectorError",
"ModelSelectorError",
"backends_declaring_model",
"normalize_backend_selector",
"normalize_model_id",
"registered_backends_sentence",
"resolve_backend_selector",
]
Loading
Loading