Skip to content

xnano.ai.models.music

xnano.ai.models.music

xnano.ai.models.music

Melodies from a language model, written in xnano's melody text and parsed into a Melody.

Classes:

Attributes:

  • Meter (TypeAlias) –

    How many beats a bar holds: '4/4', '3/4' or '2/4'.

MusicModel

MusicModel(model: Model | KnownModelName | str | None = None, *, meter: Meter = '4/4', style: str | None = None, instructions: str | None = None, model_settings: ModelSettings | None = None, capabilities: Sequence[AbstractCapability[Any]] = (), retries: int = 3, usage_limits: UsageLimits | None = None, thinking: ThinkingLevel | None = None, cache: bool = True)

Bases: TaskModel

Compose melodies: Melody in xnano's own melody text.

The model writes the melody as text, which is parsed as it arrives: a parse error, a wrong number of bars, a bar that does not hold the beats of the meter, or a pitch outside C2 to C7 goes back to the model with the fault. When the 'melodies' library of xnano.ai.assets is installed, the melodies closest to each request are shown as examples. Playing a melody needs the audio extra: pip install "xnano[audio]".

Parameters:

  • model (Model | KnownModelName | str | None, default: None ) –

    The language model to ask.

  • meter (Meter, default: '4/4' ) –

    The meter of what compose writes, unless a call gives its own.

  • style (str | None, default: None ) –

    How the music should sound, such as 'chiptune, bouncy'.

  • instructions (str | None, default: None ) –

    What the model is told before every request.

  • model_settings (ModelSettings | None, default: None ) –

    pydantic-ai settings for every request.

  • capabilities (Sequence[AbstractCapability[Any]], default: () ) –

    pydantic-ai capabilities for the agent.

  • retries (int, default: 3 ) –

    How many times a melody that fails its checks is sent back.

  • usage_limits (UsageLimits | None, default: None ) –

    Limits on the requests and tokens of one call.

  • thinking (ThinkingLevel | None, default: None ) –

    Whether the model reasons before answering. None, the default, leaves that to the model; False turns it off where the model allows it, and some models cannot turn it off.

  • cache (bool, default: True ) –

    Whether the unchanging start of every prompt is cached by the provider.

Attributes:

  • meter (Meter) –

    The meter of what compose writes.

  • last_generation (GenerationReport | None) –

    How the last call went, or None before the first.

Examples:

from xnano.ai.models.music import MusicModel
from xnano.ai.testing import scripted_model

composer = MusicModel(scripted_model({'text': 'C4 E4 G4:2 | F4 D4 C4:2'}).model)
theme = composer.compose('a cheerful march in C', bars=2, bpm=120)
assert theme.length_beats == 8.0

Create the music model; nothing is sent until the first call.

Raises:

Methods:

  • compose_async –

    Compose a melody from a description, with await.

  • compose –

    Compose a melody from a description, waiting for it.

  • vary_async –

    Write a variation of a melody, with the same bars, meter and tempo, with await.

  • vary –

    Write a variation of a melody, waiting for it.

  • override –

    Ask another model inside a with block: a test double, or a cheaper draft model.

  • details –

    What the backend reported about its last answer, as pydantic-ai's provider_details.

  • probabilities –

    The distribution a decision model gave a pick-one or rubric field in its last answer.

  • confidence –

    The confidence a decision model reported for a field of its last answer, or None.

Source code in xnano/ai/models/music.py
def __init__(
    self,
    model: Model | KnownModelName | str | None = None,
    *,
    meter: Meter = '4/4',
    style: str | None = None,
    instructions: str | None = None,
    model_settings: ModelSettings | None = None,
    capabilities: Sequence[AbstractCapability[Any]] = (),
    retries: int = 3,
    usage_limits: UsageLimits | None = None,
    thinking: ThinkingLevel | None = None,
    cache: bool = True,
) -> None:
    """
    Create the music model; nothing is sent until the first call.

    Raises:
        ValueError: ``meter`` is not one of the meters.
    """
    _check_meter(meter)
    parts = [
        'You compose short melodies for a terminal program.',
        _GRAMMAR,
        instructions or '',
    ]
    if style:
        parts.append(f'Compose in this style: {style}.')
    super().__init__(
        model,
        instructions='\n\n'.join(part for part in parts if part),
        model_settings=model_settings,
        capabilities=capabilities,
        retries=retries,
        usage_limits=usage_limits,
        thinking=thinking,
        cache=cache,
    )
    self.meter: Meter = meter
    self.style = style
    self.last_generation: GenerationReport | None = None

is_decision_model property

is_decision_model: bool

Whether model is a decision model, which answers with probabilities.

compose_async

compose_async(request: str, evidence: object = None, *, bars: int = 4, meter: Meter | None = None, bpm: float | None = None, symbol: str | None = None) -> Coroutine[Any, Any, Melody]

Compose a melody from a description, with await.

Parameters:

  • request (str) –

    What to compose, such as 'a cheerful four-bar march in C'.

  • evidence (object, default: None ) –

    What the music is for, such as the hook's context; see Evidence.

  • bars (int, default: 4 ) –

    How many bars.

  • meter (Meter | None, default: None ) –

    The meter; None uses the model's.

  • bpm (float | None, default: None ) –

    The tempo of the melody; None takes the active canvas's, or 120.

  • symbol (str | None, default: None ) –

    A name to register the melody under in symbols, so play(name) plays it.

Returns:

Raises:

  • ImportError –

    xnano-audio is not installed.

  • ValueError –

    bars is not a whole number from 1 to 32, or meter is not one of the meters.

  • GenerationError –

    No answer was a melody that passes the checks, when awaited.

Source code in xnano/ai/models/music.py
def compose_async(
    self,
    request: str,
    evidence: object = None,
    *,
    bars: int = 4,
    meter: Meter | None = None,
    bpm: float | None = None,
    symbol: str | None = None,
) -> Coroutine[Any, Any, Melody]:
    """
    Compose a melody from a description, with ``await``.

    Args:
        request: What to compose, such as ``'a cheerful four-bar march in C'``.
        evidence: What the music is for, such as the hook's context; see
            [`Evidence`][xnano.ai.Evidence].
        bars: How many bars.
        meter: The meter; ``None`` uses the model's.
        bpm: The tempo of the melody; ``None`` takes the active canvas's, or 120.
        symbol: A name to register the melody under in [`symbols`][xnano.symbols], so
            ``play(name)`` plays it.

    Returns:
        A coroutine that gives the [`Melody`][xnano.audio.Melody].

    Raises:
        ImportError: ``xnano-audio`` is not installed.
        ValueError: ``bars`` is not a whole number from 1 to 32, or ``meter`` is not one
            of the meters.
        GenerationError: No answer was a melody that passes the checks, when awaited.
    """
    require('audio', needed_for='MusicModel.compose()')
    if isinstance(bars, bool) or not isinstance(bars, int) or not 1 <= bars <= 32:
        raise ValueError(
            f'bars must be a whole number from 1 to 32, but was {bars!r}.'
        )
    chosen_meter = self.meter if meter is None else _check_meter(meter)
    return self._compose(
        request, snapshot(evidence), bars, chosen_meter, _tempo(bpm), symbol, None
    )

compose

compose(request: str, evidence: object = None, *, bars: int = 4, meter: Meter | None = None, bpm: float | None = None, symbol: str | None = None) -> Melody

Compose a melody from a description, waiting for it.

The same as compose_async.

Source code in xnano/ai/models/music.py
def compose(
    self,
    request: str,
    evidence: object = None,
    *,
    bars: int = 4,
    meter: Meter | None = None,
    bpm: float | None = None,
    symbol: str | None = None,
) -> Melody:
    """
    Compose a melody from a description, waiting for it.

    The same as [`compose_async`][xnano.ai.models.music.MusicModel.compose_async].
    """
    return _run_blocking(
        self.compose_async(
            request, evidence, bars=bars, meter=meter, bpm=bpm, symbol=symbol
        ),
        'compose',
    )

vary_async

vary_async(melody: Melody, request: str, *, symbol: str | None = None) -> Coroutine[Any, Any, Melody]

Write a variation of a melody, with the same bars, meter and tempo, with await.

Parameters:

  • melody (Melody) –

    The melody to vary; it must have bar lines, as composed melodies do.

  • request (str) –

    The change, such as 'make the last bar end on the tonic'.

  • symbol (str | None, default: None ) –

    A name to register the variation under in symbols.

Returns:

Raises:

  • ValueError –

    The melody's bars do not all hold the beats of one meter.

Source code in xnano/ai/models/music.py
def vary_async(
    self, melody: Melody, request: str, *, symbol: str | None = None
) -> Coroutine[Any, Any, Melody]:
    """
    Write a variation of a melody, with the same bars, meter and tempo, with ``await``.

    Args:
        melody: The melody to vary; it must have bar lines, as composed melodies do.
        request: The change, such as ``'make the last bar end on the tonic'``.
        symbol: A name to register the variation under in [`symbols`][xnano.symbols].

    Returns:
        A coroutine that gives the new [`Melody`][xnano.audio.Melody].

    Raises:
        ValueError: The melody's bars do not all hold the beats of one meter.
    """
    bars = melody.text.split('|')
    beats = melody.length_beats / len(bars)
    meter = next(
        (name for name, count in _BEATS_PER_BAR.items() if count == beats), None
    )
    if meter is None:
        raise ValueError(
            f'vary() needs a melody whose bars hold 2, 3 or 4 beats each, but this one '
            f'has {len(bars)} bars over {melody.length_beats:g} beats. Write it with a '
            f'bar line, |, between bars.'
        )
    return self._compose(
        request,
        None,
        len(bars),
        _check_meter(meter),
        melody.bpm,
        symbol,
        melody.text,
    )

vary

vary(melody: Melody, request: str, *, symbol: str | None = None) -> Melody

Write a variation of a melody, waiting for it.

The same as vary_async.

Source code in xnano/ai/models/music.py
def vary(self, melody: Melody, request: str, *, symbol: str | None = None) -> Melody:
    """
    Write a variation of a melody, waiting for it.

    The same as [`vary_async`][xnano.ai.models.music.MusicModel.vary_async].
    """
    return _run_blocking(self.vary_async(melody, request, symbol=symbol), 'vary')

override

override(*, model: Model | KnownModelName | str) -> Generator[None, None, None]

Ask another model inside a with block: a test double, or a cheaper draft model.

Parameters:

  • model (Model | KnownModelName | str) –

    The model to ask instead.

Examples:

from xnano.ai.models.decisions import ChoiceModel
from xnano.ai.testing import ScriptedDecisionModel

pick = ChoiceModel('typesafe:jev-1.14.0')
with pick.override(model=ScriptedDecisionModel({'response': 'left'})):
    assert pick.choose('the hero', ['left', 'right']).choice == 'left'
Source code in xnano/ai/models/__init__.py
@contextlib.contextmanager
def override(
    self, *, model: Model | KnownModelName | str
) -> Generator[None, None, None]:
    """
    Ask another model inside a ``with`` block: a test double, or a cheaper draft model.

    Args:
        model: The model to ask instead.

    Examples:
        ```python
        from xnano.ai.models.decisions import ChoiceModel
        from xnano.ai.testing import ScriptedDecisionModel

        pick = ChoiceModel('typesafe:jev-1.14.0')
        with pick.override(model=ScriptedDecisionModel({'response': 'left'})):
            assert pick.choose('the hero', ['left', 'right']).choice == 'left'
        ```
    """
    previous = self.model
    self.model = model
    try:
        with self.agent.override(model=model):
            yield
    finally:
        self.model = previous

details

details() -> dict[str, Any]

What the backend reported about its last answer, as pydantic-ai's provider_details.

Empty before the first call, and for a backend that reports nothing.

Source code in xnano/ai/models/__init__.py
def details(self) -> dict[str, Any]:
    """
    What the backend reported about its last answer, as pydantic-ai's ``provider_details``.

    Empty before the first call, and for a backend that reports nothing.
    """
    response = self._last_response()
    if response is None or response.provider_details is None:
        return {}
    return dict(response.provider_details)

probabilities

probabilities(field: str) -> dict[str, float] | None

The distribution a decision model gave a pick-one or rubric field in its last answer.

Parameters:

  • field (str) –

    The name of the field, such as 'response' for a single pick-one.

Returns:

  • dict[str, float] | None –

    The probability of each option, or None on a language model or for a field it

  • dict[str, float] | None –

    did not report.

Source code in xnano/ai/models/__init__.py
def probabilities(self, field: str) -> dict[str, float] | None:
    """
    The distribution a decision model gave a pick-one or rubric field in its last answer.

    Args:
        field: The name of the field, such as ``'response'`` for a single pick-one.

    Returns:
        The probability of each option, or ``None`` on a language model or for a field it
        did not report.
    """
    distribution = self.details().get('probabilities', {}).get(field)
    if distribution is None:
        return None
    return {str(option): float(value) for option, value in distribution.items()}

confidence

confidence(field: str) -> float | None

The confidence a decision model reported for a field of its last answer, or None.

The confidence is the backend's own figure; it is not how often the answer is right.

Source code in xnano/ai/models/__init__.py
def confidence(self, field: str) -> float | None:
    """
    The confidence a decision model reported for a field of its last answer, or ``None``.

    The confidence is the backend's own figure; it is not how often the answer is right.
    """
    value = self.details().get('confidence', {}).get(field)
    return None if value is None else float(value)