Skip to content

prices

prices

Price drift between instrument profiles and models.dev (mzt instruments prices).

Marianne prices a sheet from the models rows of the profile it ran on (cost_per_1k_input / _output / _cache_read / _cache_write). Those rows are hand-maintained and drift: the 2026-11-10 audit found 16 of 87 builtin rows wrong, Gemini under-stated up to 10x and the GPT-5.6 family on launch prices. This module compares every priced row against models.dev (https://models.dev/api.json: MIT, bot-synced, USD per million tokens, cost.{input,output,cache_read,cache_write}) and can rewrite the four price fields on the BUILTIN profiles only. User and venue layers belong to the composer; the command reports their drift and leaves the files alone.

Nothing here runs at conductor time. Prices change in a commit like any other change to a builtin, after a human reads the drift table.

Classes

PriceRow dataclass

PriceRow(profile, model, provider, status, source_path, builtin, last_updated=None, ours=dict(), theirs=dict(), drifted=())

One profile model row compared against models.dev.

Functions:

default_cache_path

default_cache_path()

Where the last fetched models.dev snapshot is kept for --offline.

Source code in src/marianne/instruments/prices.py
def default_cache_path() -> Path:
    """Where the last fetched models.dev snapshot is kept for ``--offline``."""
    return Path.home() / ".marianne" / "cache" / "models.dev.api.json"

resolve_provider

resolve_provider(profile_name, model_name)

Map a profile's model id onto (models.dev provider, models.dev id).

[1m] is Marianne's long-context suffix, not part of the provider id; a provider/id form keeps only the id. Returns (None, id) for a profile with no mapping.

Source code in src/marianne/instruments/prices.py
def resolve_provider(profile_name: str, model_name: str) -> tuple[str | None, str]:
    """Map a profile's model id onto ``(models.dev provider, models.dev id)``.

    ``[1m]`` is Marianne's long-context suffix, not part of the provider id;
    a ``provider/id`` form keeps only the id. Returns ``(None, id)`` for a
    profile with no mapping.
    """
    lookup = model_name.removesuffix("[1m]")
    rules = _PROFILE_PROVIDERS.get(profile_name.split(" (", 1)[0])
    if rules is None:
        return None, lookup
    for prefix, provider in rules:
        if lookup.startswith(prefix):
            if "/" in lookup and prefix.endswith("/"):
                lookup = lookup[len(prefix):]
            return provider, lookup
    return None, lookup

compare_profiles

compare_profiles(profiles, snapshot, *, builtins_dir)

Compare every model row of every profile against the snapshot.

profiles may hold builtins and overlays side by side (the caller loads each layer on its own, since the merged registry would hide a builtin behind a same-named user profile); a row is builtin when its file lives under builtins_dir.

Source code in src/marianne/instruments/prices.py
def compare_profiles(
    profiles: dict[str, InstrumentProfile],
    snapshot: dict[str, Any],
    *,
    builtins_dir: Path,
) -> list[PriceRow]:
    """Compare every model row of every profile against the snapshot.

    ``profiles`` may hold builtins and overlays side by side (the caller
    loads each layer on its own, since the merged registry would hide a
    builtin behind a same-named user profile); a row is ``builtin`` when
    its file lives under ``builtins_dir``.
    """
    rows: list[PriceRow] = []
    for name in sorted(profiles):
        profile = profiles[name]
        src = profile._source_path
        builtin = src is not None and src.parent == builtins_dir.resolve()
        for cap in profile.models:
            rows.append(_compare_row(name, cap, snapshot, src, builtin))
    return rows

load_layers

load_layers(builtins_dir, overlay_dirs)

Load the builtin layer and the overlay layers as two separate maps.

The registry merges layers by name, so a user claude-code.yaml would make the builtin's rows invisible to a drift report. Overlay keys are "<name> (<dir>)" so two layers that both override a name stay apart.

Source code in src/marianne/instruments/prices.py
def load_layers(
    builtins_dir: Path, overlay_dirs: list[Path],
) -> tuple[dict[str, InstrumentProfile], dict[str, InstrumentProfile]]:
    """Load the builtin layer and the overlay layers as two separate maps.

    The registry merges layers by name, so a user ``claude-code.yaml`` would
    make the builtin's rows invisible to a drift report. Overlay keys are
    ``"<name> (<dir>)"`` so two layers that both override a name stay apart.
    """
    from marianne.instruments.loader import InstrumentProfileLoader

    builtins = InstrumentProfileLoader.load_directories([builtins_dir])
    overlays: dict[str, InstrumentProfile] = {}
    for d in overlay_dirs:
        if not d.is_dir():
            continue
        for name, prof in InstrumentProfileLoader.load_directories(
            [d], lower_layers=[builtins_dir, *overlay_dirs[: overlay_dirs.index(d)]],
        ).items():
            overlays[f"{name} ({d})"] = prof
    return builtins, overlays

rewrite_builtin_prices

rewrite_builtin_prices(text, model, prices)

Rewrite the price fields of one - name: <model> block in profile YAML text.

Text-level so the file's comments survive. A field models.dev prices and the block lacks is inserted after cost_per_1k_output; a field models.dev does not price is left as it is.

Source code in src/marianne/instruments/prices.py
def rewrite_builtin_prices(text: str, model: str, prices: dict[str, float | None]) -> str:
    """Rewrite the price fields of one ``- name: <model>`` block in profile YAML text.

    Text-level so the file's comments survive. A field models.dev prices and
    the block lacks is inserted after ``cost_per_1k_output``; a field
    models.dev does not price is left as it is.
    """
    lines = text.split("\n")
    start = None
    for i, line in enumerate(lines):
        m = _NAME_LINE.match(line)
        if m and m.group("name") == model:
            start = i
            break
    if start is None:
        raise KeyError(f"model row {model!r} not found")
    indent = len(lines[start]) - len(lines[start].lstrip())
    end = len(lines)
    for j in range(start + 1, len(lines)):
        stripped = lines[j].strip()
        if not stripped or stripped.startswith("#"):
            continue
        cur = len(lines[j]) - len(lines[j].lstrip())
        if cur <= indent:
            end = j
            break
    block = lines[start:end]
    field_indent = " " * (indent + 2)
    present: dict[str, int] = {}
    for k, line in enumerate(block):
        m2 = re.match(r"^\s*(cost_per_1k_\w+):", line)
        if m2:
            present[m2.group(1)] = k
    for f in PRICE_FIELDS:
        value = prices.get(f)
        if value is None:
            continue
        new_line = f"{field_indent}{f}: {_fmt(value)}"
        if f in present:
            k = present[f]
            comment = ""
            cm = re.search(r"\s+#.*$", block[k])
            if cm:
                comment = cm.group(0)
            block[k] = new_line + comment
        else:
            anchor = present.get("cost_per_1k_output", present.get("cost_per_1k_input"))
            if anchor is None:
                raise KeyError(f"model row {model!r} has no cost_per_1k_output line to anchor on")
            # Keep insertion order: cache_read before cache_write.
            insert_at = anchor + 1
            for prior in PRICE_FIELDS[: PRICE_FIELDS.index(f)]:
                if prior in present and present[prior] > anchor:
                    insert_at = max(insert_at, present[prior] + 1)
            block.insert(insert_at, new_line)
            present = {
                name: (idx + 1 if idx >= insert_at else idx) for name, idx in present.items()
            }
            present[f] = insert_at
    return "\n".join(lines[:start] + block + lines[end:])

apply_drift

apply_drift(rows, *, builtins_dir)

Write drifted builtin rows back to their YAML files.

Returns (written, refused): refused rows are drifted rows whose file is not under the builtins directory (the composer's layer).

Source code in src/marianne/instruments/prices.py
def apply_drift(
    rows: list[PriceRow], *, builtins_dir: Path,
) -> tuple[list[PriceRow], list[PriceRow]]:
    """Write drifted builtin rows back to their YAML files.

    Returns ``(written, refused)``: refused rows are drifted rows whose file
    is not under the builtins directory (the composer's layer).
    """
    written: list[PriceRow] = []
    refused: list[PriceRow] = []
    by_file: dict[Path, list[PriceRow]] = {}
    for r in rows:
        if r.status != "drift":
            continue
        if not r.builtin or r.source_path is None or r.source_path.parent != builtins_dir.resolve():
            refused.append(r)
            continue
        by_file.setdefault(r.source_path, []).append(r)
    for path, file_rows in by_file.items():
        text = path.read_text(encoding="utf-8")
        for r in file_rows:
            text = rewrite_builtin_prices(text, r.model, r.theirs)
            written.append(r)
        path.write_text(text, encoding="utf-8")
    return written, refused

fetch_snapshot

fetch_snapshot(*, timeout=20.0)

GET models.dev api.json. Raises on any transport or shape failure.

Source code in src/marianne/instruments/prices.py
def fetch_snapshot(*, timeout: float = 20.0) -> dict[str, Any]:
    """GET models.dev api.json. Raises on any transport or shape failure."""
    import httpx

    resp = httpx.get(MODELS_DEV_URL, timeout=timeout, follow_redirects=True)
    resp.raise_for_status()
    data = resp.json()
    if not isinstance(data, dict) or not data:
        raise ValueError("models.dev returned no providers")
    return data