Skip to content

xnano.ai.models

xnano.ai.models

xnano.ai.models

Task models: each asks a model for one kind of thing and returns xnano values.

Every task model is a TaskModel, which owns one pydantic-ai agent with its instructions and settings, and lives in a module named for what it makes: decisions (ChoiceModel, JudgeModel), state (StateModel), text (TextModel), art (ArtModel), components (ComponentModel) and music (MusicModel). Each task model is exported here too, so from xnano.ai.models import ArtModel works.

Modules:

  • art –

    xnano.ai.models.art

  • components –

    xnano.ai.models.components

  • decisions –

    xnano.ai.models.decisions

  • music –

    xnano.ai.models.music

  • state –

    xnano.ai.models.state

  • text –

    xnano.ai.models.text

Classes:

  • TaskModel –

    A model with one job: an agent with its instructions and settings, behind methods that take

  • ArtModel –

    Generate and edit pixel art: xnano.Art from a description.

  • ComponentModel –

    Generate widgets: a status card, a menu, a table, as a small program that draws them.

  • ChoiceModel –

    Pick one of a few options for what is on the canvas.

  • JudgeModel –

    Answer yes/no questions, and place evidence on a rubric.

  • MusicModel –

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

  • StateModel –

    Keep a small state up to date as things happen.

  • TextModel –

    Write prose for the canvas: a description, a narration, a line of dialogue.

Functions:

  • is_decision_model –

    Whether a model answers typed questions with probabilities instead of writing text.

  • run_to_completion –

    Run an awaitable from code that does not await, and return its result.

TaskModel

TaskModel(model: Model | KnownModelName | 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)

A model with one job: an agent with its instructions and settings, behind methods that take xnano objects and return xnano objects.

Every task model (ChoiceModel, ArtModel, ...) is built on this. Each method that asks a model has two spellings: the plain one waits for the answer, and the _async one is a coroutine for code that awaits. A task model can be created without credentials; the model is reached at the first call.

Parameters:

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

    The model to ask: a pydantic-ai Model, one of pydantic-ai's known model names such as 'typesafe:jev-latest', or any other name its providers take, such as 'typesafe:jev-1.14.0' or 'openrouter:anthropic/claude-sonnet-5-5'.

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

    What the model is told before every request, after the task model's own instructions.

  • 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 an answer that fails its checks is sent back to be fixed.

  • 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:

  • model (Model | KnownModelName | str | None) –

    The model the task model asks.

  • agent (Agent[None, Any]) –

    The pydantic-ai Agent, for anything the task model does not expose.

  • last_result (AgentRunResult[Any] | None) –

    The result of the last call, or None before the first.

  • is_decision_model (bool) –

    Whether model is a decision model.

Examples:

from xnano.ai.models.decisions import ChoiceModel

pick = ChoiceModel('typesafe:jev-1.14.0')
assert pick.is_decision_model and pick.last_result is None

Create the task model and its agent; nothing is sent until the first call.

Raises:

  • ValueError –

    retries is not a whole number of 0 or more.

Methods:

  • 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/__init__.py
def __init__(
    self,
    model: Model | KnownModelName | 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 task model and its agent; nothing is sent until the first call.

    Raises:
        ValueError: ``retries`` is not a whole number of 0 or more.
    """
    if isinstance(retries, bool) or not isinstance(retries, int) or retries < 0:
        raise ValueError(
            f'retries must be a whole number of 0 or more, but was {retries!r}. It is how '
            f'many times an answer that fails its checks is sent back, such as retries=3.'
        )
    self.model: Model | KnownModelName | str | None = model
    self._instructions = instructions
    settings: dict[str, object] = dict(model_settings or {})
    if thinking is not None:
        settings.setdefault('thinking', thinking)
    if cache:
        settings.setdefault('cache', True)
    self._model_settings = settings
    self._usage_limits = usage_limits
    self.agent: Agent[None, Any] = Agent(
        model,
        instructions=self._joined_instructions() or None,
        model_settings=settings,  # type: ignore[arg-type]
        capabilities=list(capabilities),
        retries={'output': retries},
        defer_model_check=True,
    )
    self.last_result: AgentRunResult[Any] | None = None

is_decision_model property

is_decision_model: bool

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

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)

ArtModel

ArtModel(model: Model | KnownModelName | str | None = None, *, strategy: ArtStrategy = 'program', width: ArtSize = (None, _DEFAULT_MOST), height: ArtSize = (None, _DEFAULT_MOST), max_colors: int | None = None, style: str | None = None, critique: int = 0, critic: Model | KnownModelName | str | None = None, image_model: ImageGenerationModel | 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

Generate and edit pixel art: xnano.Art from a description.

A piece larger than 12 pixels is drawn in two steps. First the model sketches it: the size, a palette of its masses (hair, face, body), and a few big shapes on a grid of blocks of 2 by 2 pixels, which settles the proportions and the placement of each part. Then it draws the piece at full size over that sketch, in the form of its strategy, as flat colours: one base colour per material, and the details; a drawing that leaves the composition of its sketch is sent back. A piece of 12 pixels or less is drawn in one step. The renderer then finishes the piece the way a pixel artist does, with the light from the top left: lone pixels take the colour around them, the silhouette gets an outline inside it in a dark colour of its own, and each material gets a shadow along its lower-right edges and a highlight along its upper-left edges, in colours shifted in hue. The model names its colours by role (base, skin, detail, accent, and outline, shadow or highlight when it draws those itself, which the renderer then leaves alone) under letters. Every answer is checked as it arrives: a size outside the range, an unknown letter, too many colours or a program that fails goes back to the model with the exact fault. A safe repair (a colour written '#f8c', a code fence around the program) is made instead of a retry and reported in last_generation, as is what the renderer added. Built-in references, the two closest to each request, show the craft in the strategy's own form; the 'art-references' library of xnano.ai.assets adds more when it is installed.

An image_model draws the piece as a picture instead: an image model paints the sprite scaled up on a flat background, and the picture's own pixel grid is read back into pixel art, one sample per drawn pixel, the background keyed out, the sprite cropped to its bounds and shrunk by a whole factor when it is larger than asked, and its colours reduced to the palette. The language model then edits and critiques that art as it does any other.

Parameters:

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

    The language model to ask.

  • strategy (ArtStrategy, default: 'program' ) –

    How the model writes the art: 'program' (the default: a short program of rectangles, ellipses, polygons, mirroring and an outline) or 'svg' (an SVG drawing, for round and diagonal forms).

  • width (ArtSize, default: (None, _DEFAULT_MOST) ) –

    The width of what generate makes, in the forms of ArtSize; each call can give its own.

  • height (ArtSize, default: (None, _DEFAULT_MOST) ) –

    The height, in the same forms.

  • max_colors (int | None, default: None ) –

    The most colours a piece may have; None scales with the size, from about 5 at 8 by 8 to 16 at 32 by 32.

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

    How the art should look, such as 'chunky outlines, warm palette'.

  • critique (int, default: 0 ) –

    How many rounds of critique generate runs, unless a call gives its own: in each, a vision model sees the piece as an image and lists what to fix, the model draws it again, and the piece with the best score is kept. 0 by default.

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

    The vision model that critiques; None asks model, which must then see images.

  • image_model (ImageGenerationModel | str | None, default: None ) –

    An image generation model that draws the piece as a picture, by name ('openrouter:google/gemini-2.5-flash-image', or one pydantic-ai knows such as 'openai:gpt-image-1') or as a pydantic-ai ImageGenerationModel; None draws with model in the form of strategy.

  • 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 an answer 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:

  • strategy (ArtStrategy) –

    How the model writes the art.

  • critique –

    How many rounds of critique generate runs.

  • critic –

    The vision model that critiques, or None for the model itself.

  • image_model –

    The image generation model that draws, or None.

  • last_generation (GenerationReport | None) –

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

Examples:

from xnano.ai.models.art import ArtModel, ArtText
from xnano.ai.testing import scripted_model

answer = {
    'layout': 'A coin filling the canvas.',
    'palette': [
        {'letter': 'o', 'role': 'outline', 'color': '#1a1c2c'},
        {'letter': 'y', 'role': 'base', 'color': '#ffcd75'},
    ],
    'width': 4,
    'height': 4,
    'program': "ellipse(0, 0, W, H, 'o'); rect(1, 1, 2, 2, 'y')",
}
artist = ArtModel(scripted_model(answer).model, width=4, height=4)
coin = artist.generate('a gold coin')
assert ArtText.from_art(coin).rows == ('.oo.', 'oyyo', 'oyyo', '.oo.')
assert artist.last_generation.attempts == 1

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

Raises:

  • ValueError –

    strategy is not one of the strategies, max_colors is not a whole number from 2 to 25, or critique is not a whole number from 0 to 3.

Methods:

  • 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.

  • generate_async –

    Draw pixel art from a description, with await.

  • generate –

    Draw pixel art from a description, waiting for it.

  • edit_async –

    Change pixel art as asked, with await: a patch of the pixels that change.

  • edit –

    Change pixel art as asked, waiting for it.

  • variants_async –

    Make one edit of the art for each request, all at once, with await.

  • variants –

    Make one edit of the art for each request, all at once, waiting for them.

  • animate_async –

    Animate pixel art, with await: one patch of the art for each frame.

  • animate –

    Animate pixel art, waiting for it.

Source code in xnano/ai/models/art.py
def __init__(
    self,
    model: Model | KnownModelName | str | None = None,
    *,
    strategy: ArtStrategy = 'program',
    width: ArtSize = (None, _DEFAULT_MOST),
    height: ArtSize = (None, _DEFAULT_MOST),
    max_colors: int | None = None,
    style: str | None = None,
    critique: int = 0,
    critic: Model | KnownModelName | str | None = None,
    image_model: ImageGenerationModel | 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 art model; nothing is sent until the first call.

    Raises:
        ValueError: ``strategy`` is not one of the strategies, ``max_colors`` is not a
            whole number from 2 to 25, or ``critique`` is not a whole number from 0 to 3.
    """
    _check_critique(critique)
    if strategy not in _STRATEGY_INSTRUCTIONS:
        raise ValueError(
            f"strategy must be 'program' or 'svg', but was {strategy!r}."
        )
    if max_colors is not None and (
        isinstance(max_colors, bool)
        or not isinstance(max_colors, int)
        or not 2 <= max_colors <= 25
    ):
        raise ValueError(
            f'max_colors must be a whole number from 2 to 25, or None, but was '
            f'{max_colors!r}.'
        )
    parts = [
        _STRATEGY_INSTRUCTIONS[strategy],
        _SKETCH_INSTRUCTIONS,
        instructions or '',
    ]
    if style:
        parts.append(f'Draw 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.strategy: ArtStrategy = strategy
    self.style = style
    self._width = width
    self._height = height
    self._max_colors = max_colors
    self.critique = critique
    self.critic = critic
    self.image_model = image_model
    self.last_generation: GenerationReport | None = None

is_decision_model property

is_decision_model: bool

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

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)

generate_async

generate_async(request: str, evidence: object = None, *, width: ArtSize = None, height: ArtSize = None, symmetrical: bool = False, braille: bool = False, borders: bool = False, candidates: int = 1, critique: int | None = None, symbol: str | None = None) -> Coroutine[Any, Any, Art]

Draw pixel art from a description, with await.

The sizes are read when this is called; await the result for the art.

Parameters:

  • request (str) –

    What to draw, such as 'a knight with a red plume'.

  • evidence (object, default: None ) –

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

  • width (ArtSize, default: None ) –

    The width; None uses the model's.

  • height (ArtSize, default: None ) –

    The height; None uses the model's.

  • symmetrical (bool, default: False ) –

    Whether the piece is symmetric about its vertical middle, like a face or a creature seen from the front. The model then draws only the left half, which is mirrored to make the right half (an odd width shares its middle column), so the two sides match exactly. False by default.

  • braille (bool, default: False ) –

    Whether the art shows as braille dots, two by four per terminal cell in one colour per cell: a finer, drawing-like look that pixel art cannot have. The model is told, and draws for it. False by default.

  • borders (bool, default: False ) –

    Whether the art shows one pixel per cell, its edge traced in box-drawing characters and its inside filled with colour: the look of a terminal, which pixel art cannot have. The model is told that a cell is twice as tall as it is wide, and draws for it. False by default.

  • candidates (int, default: 1 ) –

    How many pieces to draw at once; the one that is valid, within its colours and the most connected is kept.

  • critique (int | None, default: None ) –

    How many rounds of critique to run; None uses the model's. See Critique.

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

    A name to register the art under in symbols.

Returns:

Raises:

  • ValueError –

    A size is not one of the forms of ArtSize, candidates is not 1 or more, or critique is not a whole number from 0 to 3.

  • GenerationError –

    No answer could be made into the art, even after the retries; its generation lists every problem, when awaited.

  • TerminalError –

    The model could not be reached (ai.model), when awaited.

Source code in xnano/ai/models/art.py
def generate_async(
    self,
    request: str,
    evidence: object = None,
    *,
    width: ArtSize = None,
    height: ArtSize = None,
    symmetrical: bool = False,
    braille: bool = False,
    borders: bool = False,
    candidates: int = 1,
    critique: int | None = None,
    symbol: str | None = None,
) -> Coroutine[Any, Any, Art]:
    """
    Draw pixel art from a description, with ``await``.

    The sizes are read when this is called; await the result for the art.

    Args:
        request: What to draw, such as ``'a knight with a red plume'``.
        evidence: What the art is for, such as the hook's context; see
            [`Evidence`][xnano.ai.Evidence].
        width: The width; ``None`` uses the model's.
        height: The height; ``None`` uses the model's.
        symmetrical: Whether the piece is symmetric about its vertical middle, like a
            face or a creature seen from the front. The model then draws only the left
            half, which is mirrored to make the right half (an odd width shares its
            middle column), so the two sides match exactly. ``False`` by default.
        braille: Whether the art shows as braille dots, two by four per terminal cell in
            one colour per cell: a finer, drawing-like look that pixel art cannot have.
            The model is told, and draws for it. ``False`` by default.
        borders: Whether the art shows one pixel per cell, its edge traced in box-drawing
            characters and its inside filled with colour: the look of a terminal, which
            pixel art cannot have. The model is told that a cell is twice as tall as it
            is wide, and draws for it. ``False`` by default.
        candidates: How many pieces to draw at once; the one that is valid, within its
            colours and the most connected is kept.
        critique: How many rounds of critique to run; ``None`` uses the model's. See
            [`Critique`][xnano.ai.Critique].
        symbol: A name to register the art under in [`symbols`][xnano.symbols].

    Returns:
        A coroutine that gives the [`Art`][xnano.art.Art].

    Raises:
        ValueError: A size is not one of the forms of ``ArtSize``, ``candidates`` is not
            1 or more, or ``critique`` is not a whole number from 0 to 3.
        GenerationError: No answer could be made into the art, even after the retries;
            its ``generation`` lists every problem, when awaited.
        TerminalError: The model could not be reached (``ai.model``), when awaited.
    """
    widths = _pixel_range(self._width if width is None else width, 'width')
    heights = _pixel_range(self._height if height is None else height, 'height')
    if (
        isinstance(candidates, bool)
        or not isinstance(candidates, int)
        or candidates < 1
    ):
        raise ValueError(
            f'candidates must be a whole number of 1 or more, but was {candidates!r}.'
        )
    for name, flag in (
        ('symmetrical', symmetrical),
        ('braille', braille),
        ('borders', borders),
    ):
        if not isinstance(flag, bool):
            raise ValueError(f'{name} must be True or False, but was {flag!r}.')
    rounds = self.critique if critique is None else _check_critique(critique)
    return self._generate(
        request,
        snapshot(evidence),
        widths,
        heights,
        _Look(symmetrical, braille, borders),
        candidates,
        rounds,
        symbol,
    )

generate

generate(request: str, evidence: object = None, *, width: ArtSize = None, height: ArtSize = None, symmetrical: bool = False, braille: bool = False, borders: bool = False, candidates: int = 1, critique: int | None = None, symbol: str | None = None) -> Art

Draw pixel art from a description, waiting for it.

The same as generate_async, for code that does not await.

Source code in xnano/ai/models/art.py
def generate(
    self,
    request: str,
    evidence: object = None,
    *,
    width: ArtSize = None,
    height: ArtSize = None,
    symmetrical: bool = False,
    braille: bool = False,
    borders: bool = False,
    candidates: int = 1,
    critique: int | None = None,
    symbol: str | None = None,
) -> Art:
    """
    Draw pixel art from a description, waiting for it.

    The same as [`generate_async`][xnano.ai.models.art.ArtModel.generate_async], for code that does
    not await.
    """
    return _run_blocking(
        self.generate_async(
            request,
            evidence,
            width=width,
            height=height,
            symmetrical=symmetrical,
            braille=braille,
            borders=borders,
            candidates=candidates,
            critique=critique,
            symbol=symbol,
        ),
        'generate',
    )

edit_async

edit_async(art: Art, request: str, *, protect: Sequence[str] = (), allow_new_colors: bool = False, max_changes: float = 0.5, mode: EditMode = 'auto', symbol: str | None = None) -> Coroutine[Any, Any, Art]

Change pixel art as asked, with await: a patch of the pixels that change.

The art itself is not changed: a new Art is returned, so when the edit fails the art you had is still there.

Parameters:

  • art (Art) –

    The art to change.

  • request (str) –

    The change, such as 'give the knight a blue cape'.

  • protect (Sequence[str], default: () ) –

    Roles or letters whose pixels must not change, such as ['outline', 'skin'].

  • allow_new_colors (bool, default: False ) –

    Whether the edit may add colours to the palette.

  • max_changes (float, default: 0.5 ) –

    The largest share of the drawn pixels a patch may change; a larger change is drawn again whole (mode='auto') or refused.

  • mode (EditMode, default: 'auto' ) –

    'patch', 'redraw', or 'auto' for the model to choose.

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

    A name to register the new art under in symbols.

Returns:

Raises:

  • ValueError –

    mode or max_changes is out of range, or protect names a role or letter the art does not have.

  • GenerationError –

    No answer made a valid edit, when awaited.

Source code in xnano/ai/models/art.py
def edit_async(
    self,
    art: Art,
    request: str,
    *,
    protect: Sequence[str] = (),
    allow_new_colors: bool = False,
    max_changes: float = 0.5,
    mode: EditMode = 'auto',
    symbol: str | None = None,
) -> Coroutine[Any, Any, Art]:
    """
    Change pixel art as asked, with ``await``: a patch of the pixels that change.

    The art itself is not changed: a new [`Art`][xnano.art.Art] is returned, so when the
    edit fails the art you had is still there.

    Args:
        art: The art to change.
        request: The change, such as ``'give the knight a blue cape'``.
        protect: Roles or letters whose pixels must not change, such as
            ``['outline', 'skin']``.
        allow_new_colors: Whether the edit may add colours to the palette.
        max_changes: The largest share of the drawn pixels a patch may change; a
            larger change is drawn again whole (``mode='auto'``) or refused.
        mode: ``'patch'``, ``'redraw'``, or ``'auto'`` for the model to choose.
        symbol: A name to register the new art under in [`symbols`][xnano.symbols].

    Returns:
        A coroutine that gives the new art.

    Raises:
        ValueError: ``mode`` or ``max_changes`` is out of range, or ``protect`` names a
            role or letter the art does not have.
        GenerationError: No answer made a valid edit, when awaited.
    """
    if mode not in ('auto', 'patch', 'redraw'):
        raise ValueError(
            f"mode must be 'auto', 'patch' or 'redraw', but was {mode!r}."
        )
    if isinstance(max_changes, bool) or not 0 < max_changes <= 1:
        raise ValueError(
            f'max_changes must be a share above 0 and at most 1, such as 0.5, but was '
            f'{max_changes!r}.'
        )
    text = ArtText.from_art(art)
    protected = _protected_letters(text, protect)
    return self._edit(
        text, request, protected, allow_new_colors, max_changes, mode, symbol
    )

edit

edit(art: Art, request: str, *, protect: Sequence[str] = (), allow_new_colors: bool = False, max_changes: float = 0.5, mode: EditMode = 'auto', symbol: str | None = None) -> Art

Change pixel art as asked, waiting for it.

The same as edit_async.

Examples:

from xnano.ai.models.art import ArtModel, ArtText, PaletteColor
from xnano.ai.testing import scripted_model

coin = ArtText(
    rows=('.oo.', 'oyyo', '.oo.'),
    palette={
        'o': PaletteColor('outline', '#1a1c2c'),
        'y': PaletteColor('base', '#ffcd75'),
    },
).to_art()
patch = {'runs': [{'row': 1, 'column': 1, 'letters': 'oo'}], 'new_colors': []}
artist = ArtModel(scripted_model(('patch', patch)).model)
dented = artist.edit(coin, 'put a dent in the middle')
assert dented.pixel(1, 1) == coin.pixel(0, 1)
Source code in xnano/ai/models/art.py
def edit(
    self,
    art: Art,
    request: str,
    *,
    protect: Sequence[str] = (),
    allow_new_colors: bool = False,
    max_changes: float = 0.5,
    mode: EditMode = 'auto',
    symbol: str | None = None,
) -> Art:
    """
    Change pixel art as asked, waiting for it.

    The same as [`edit_async`][xnano.ai.models.art.ArtModel.edit_async].

    Examples:
        ```python
        from xnano.ai.models.art import ArtModel, ArtText, PaletteColor
        from xnano.ai.testing import scripted_model

        coin = ArtText(
            rows=('.oo.', 'oyyo', '.oo.'),
            palette={
                'o': PaletteColor('outline', '#1a1c2c'),
                'y': PaletteColor('base', '#ffcd75'),
            },
        ).to_art()
        patch = {'runs': [{'row': 1, 'column': 1, 'letters': 'oo'}], 'new_colors': []}
        artist = ArtModel(scripted_model(('patch', patch)).model)
        dented = artist.edit(coin, 'put a dent in the middle')
        assert dented.pixel(1, 1) == coin.pixel(0, 1)
        ```
    """
    return _run_blocking(
        self.edit_async(
            art,
            request,
            protect=protect,
            allow_new_colors=allow_new_colors,
            max_changes=max_changes,
            mode=mode,
            symbol=symbol,
        ),
        'edit',
    )

variants_async

variants_async(art: Art, requests: Sequence[str], **edit_options: Any) -> Coroutine[Any, Any, list[Art]]

Make one edit of the art for each request, all at once, with await.

Parameters:

  • art (Art) –

    The art to change.

  • requests (Sequence[str]) –

    One change for each variant, such as ['winter coat', 'chain mail'].

  • edit_options (Any, default: {} ) –

    The keywords of edit, for every variant.

Returns:

Source code in xnano/ai/models/art.py
def variants_async(
    self, art: Art, requests: Sequence[str], **edit_options: Any
) -> Coroutine[Any, Any, list[Art]]:
    """
    Make one edit of the art for each request, all at once, with ``await``.

    Args:
        art: The art to change.
        requests: One change for each variant, such as ``['winter coat', 'chain mail']``.
        edit_options: The keywords of [`edit`][xnano.ai.models.art.ArtModel.edit], for every
            variant.

    Returns:
        A coroutine that gives the variants, in the order of the requests.
    """
    edits = [self.edit_async(art, request, **edit_options) for request in requests]

    async def gather() -> list[Art]:
        return list(await asyncio.gather(*edits))

    return gather()

variants

variants(art: Art, requests: Sequence[str], **edit_options: Any) -> list[Art]

Make one edit of the art for each request, all at once, waiting for them.

The same as variants_async.

Source code in xnano/ai/models/art.py
def variants(
    self, art: Art, requests: Sequence[str], **edit_options: Any
) -> list[Art]:
    """
    Make one edit of the art for each request, all at once, waiting for them.

    The same as [`variants_async`][xnano.ai.models.art.ArtModel.variants_async].
    """
    return _run_blocking(
        self.variants_async(art, requests, **edit_options), 'variants'
    )

animate_async

animate_async(art: Art, request: str, *, frames: int = 2, fps: float = 4.0) -> Coroutine[Any, Any, Animation]

Animate pixel art, with await: one patch of the art for each frame.

Every frame is a patch of the same base art, so the frames never drift away from it.

Parameters:

  • art (Art) –

    The art to animate.

  • request (str) –

    The motion, such as 'a two-frame idle bob'.

  • frames (int, default: 2 ) –

    How many frames.

  • fps (float, default: 4.0 ) –

    How many frames are shown each second.

Returns:

Raises:

  • ValueError –

    frames is not a whole number from 2 to 16, or fps is not above 0.

  • GenerationError –

    No answer made valid frames, when awaited.

Source code in xnano/ai/models/art.py
def animate_async(
    self, art: Art, request: str, *, frames: int = 2, fps: float = 4.0
) -> Coroutine[Any, Any, Animation]:
    """
    Animate pixel art, with ``await``: one patch of the art for each frame.

    Every frame is a patch of the same base art, so the frames never drift away from it.

    Args:
        art: The art to animate.
        request: The motion, such as ``'a two-frame idle bob'``.
        frames: How many frames.
        fps: How many frames are shown each second.

    Returns:
        A coroutine that gives the [`Animation`][xnano.ai.models.art.Animation].

    Raises:
        ValueError: ``frames`` is not a whole number from 2 to 16, or ``fps`` is not
            above 0.
        GenerationError: No answer made valid frames, when awaited.
    """
    if (
        isinstance(frames, bool)
        or not isinstance(frames, int)
        or not 2 <= frames <= 16
    ):
        raise ValueError(
            f'frames must be a whole number from 2 to 16, but was {frames!r}.'
        )
    if isinstance(fps, bool) or not fps > 0:
        raise ValueError(f'fps must be above 0, such as 4, but was {fps!r}.')
    return self._animate(ArtText.from_art(art), request, frames, float(fps))

animate

animate(art: Art, request: str, *, frames: int = 2, fps: float = 4.0) -> Animation

Animate pixel art, waiting for it.

The same as animate_async.

Source code in xnano/ai/models/art.py
def animate(
    self, art: Art, request: str, *, frames: int = 2, fps: float = 4.0
) -> Animation:
    """
    Animate pixel art, waiting for it.

    The same as [`animate_async`][xnano.ai.models.art.ArtModel.animate_async].
    """
    return _run_blocking(
        self.animate_async(art, request, frames=frames, fps=fps), 'animate'
    )

ComponentModel

ComponentModel(model: Model | KnownModelName | str | None = None, *, max_width: int = 48, max_height: int = 12, instructions: str | None = None, model_settings: ModelSettings | None = None, capabilities: Sequence[AbstractCapability[Any]] = (), retries: int = 2, usage_limits: UsageLimits | None = None, thinking: ThinkingLevel | None = None, cache: bool = True)

Bases: TaskModel

Generate widgets: a status card, a menu, a table, as a small program that draws them.

The model is given the drawing API of the sandbox and worked examples, each with what it draws, and writes a program at the size asked for. The program is run in the sandbox of xnano.sandbox as it arrives. What can be fixed safely is fixed and reported in last_generation.notes: a near-miss border or colour name, a keyword the API does not take, a cell outside the canvas, a line too long for it. An error, something else drawn outside the size, or nothing drawn at all goes back to the model with what it drew so far, under a column ruler. When the 'component-examples' library of xnano.ai.assets is installed, the examples closest to each request are shown too.

Parameters:

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

    The language model to ask.

  • max_width (int, default: 48 ) –

    The widest component a call may ask for, in cells.

  • max_height (int, default: 12 ) –

    The tallest component a call may ask for, in rows.

  • 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: 2 ) –

    How many times a program that fails 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:

  • last_generation (GenerationReport | None) –

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

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

Raises:

  • ValueError –

    max_width or max_height is not a whole number of 1 or more.

Methods:

  • 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.

  • generate_async –

    Write a widget from a description, with await.

  • generate –

    Write a widget from a description, waiting for it.

  • edit_async –

    Change a widget as asked, at the same size, with await.

  • edit –

    Change a widget as asked, waiting for it.

Source code in xnano/ai/models/components.py
def __init__(
    self,
    model: Model | KnownModelName | str | None = None,
    *,
    max_width: int = 48,
    max_height: int = 12,
    instructions: str | None = None,
    model_settings: ModelSettings | None = None,
    capabilities: Sequence[AbstractCapability[Any]] = (),
    retries: int = 2,
    usage_limits: UsageLimits | None = None,
    thinking: ThinkingLevel | None = None,
    cache: bool = True,
) -> None:
    """
    Create the component model; nothing is sent until the first call.

    Raises:
        ValueError: ``max_width`` or ``max_height`` is not a whole number of 1 or more.
    """
    for name, value in (('max_width', max_width), ('max_height', max_height)):
        if isinstance(value, bool) or not isinstance(value, int) or value < 1:
            raise ValueError(
                f'{name} must be a whole number of 1 or more, but was {value!r}.'
            )
    super().__init__(
        model,
        instructions='\n\n'.join(
            part for part in (_instructions(), instructions) if part
        ),
        model_settings=model_settings,
        capabilities=capabilities,
        retries=retries,
        usage_limits=usage_limits,
        thinking=thinking,
        cache=cache,
    )
    self.max_width = max_width
    self.max_height = max_height
    self.last_generation: GenerationReport | None = None

is_decision_model property

is_decision_model: bool

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

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)

generate_async

generate_async(request: str, evidence: object = None, *, width: int | None = None, height: int | None = None) -> Coroutine[Any, Any, Component]

Write a widget from a description, with await.

Parameters:

  • request (str) –

    What to draw, such as 'a status card: CPU 73%, memory 41%'.

  • evidence (object, default: None ) –

    What the widget shows, such as the hook's context; see Evidence.

  • width (int | None, default: None ) –

    The width in cells; None is max_width.

  • height (int | None, default: None ) –

    The height in rows; None is max_height.

Returns:

Raises:

  • ValueError –

    A size is not a whole number from 1 to the model's most.

  • GenerationError –

    No program drew the widget, even after the retries, when awaited.

Source code in xnano/ai/models/components.py
def generate_async(
    self,
    request: str,
    evidence: object = None,
    *,
    width: int | None = None,
    height: int | None = None,
) -> Coroutine[Any, Any, Component]:
    """
    Write a widget from a description, with ``await``.

    Args:
        request: What to draw, such as ``'a status card: CPU 73%, memory 41%'``.
        evidence: What the widget shows, such as the hook's context; see
            [`Evidence`][xnano.ai.Evidence].
        width: The width in cells; ``None`` is ``max_width``.
        height: The height in rows; ``None`` is ``max_height``.

    Returns:
        A coroutine that gives the [`Component`][xnano.ai.models.components.Component].

    Raises:
        ValueError: A size is not a whole number from 1 to the model's most.
        GenerationError: No program drew the widget, even after the retries, when
            awaited.
    """
    size = (self._check_size(width, 'width'), self._check_size(height, 'height'))
    return self._write(request, snapshot(evidence), size, None)

generate

generate(request: str, evidence: object = None, *, width: int | None = None, height: int | None = None) -> Component

Write a widget from a description, waiting for it.

The same as generate_async.

Source code in xnano/ai/models/components.py
def generate(
    self,
    request: str,
    evidence: object = None,
    *,
    width: int | None = None,
    height: int | None = None,
) -> Component:
    """
    Write a widget from a description, waiting for it.

    The same as [`generate_async`][xnano.ai.models.components.ComponentModel.generate_async].
    """
    return _run_blocking(
        self.generate_async(request, evidence, width=width, height=height), 'generate'
    )

edit_async

edit_async(component: Component, request: str) -> Coroutine[Any, Any, Component]

Change a widget as asked, at the same size, with await.

Parameters:

  • component (Component) –

    The widget to change.

  • request (str) –

    The change, such as 'turn the CPU bar red'.

Returns:

Source code in xnano/ai/models/components.py
def edit_async(
    self, component: Component, request: str
) -> Coroutine[Any, Any, Component]:
    """
    Change a widget as asked, at the same size, with ``await``.

    Args:
        component: The widget to change.
        request: The change, such as ``'turn the CPU bar red'``.

    Returns:
        A coroutine that gives the new [`Component`][xnano.ai.models.components.Component]; the one given
        is not changed.
    """
    return self._write(request, None, (component.width, component.height), component)

edit

edit(component: Component, request: str) -> Component

Change a widget as asked, waiting for it.

The same as edit_async.

Source code in xnano/ai/models/components.py
def edit(self, component: Component, request: str) -> Component:
    """
    Change a widget as asked, waiting for it.

    The same as [`edit_async`][xnano.ai.models.components.ComponentModel.edit_async].
    """
    return _run_blocking(self.edit_async(component, request), 'edit')

ChoiceModel

ChoiceModel(*arguments: Any, **keywords: Any)

Bases: _AskingModel

Pick one of a few options for what is on the canvas.

On a decision model ('typesafe:jev-1.14.0') the answer comes with the probability of every option, so a program can act only when the pick is clear. A named no_change option is always offered first, because "keep things as they are" is a better answer than a forced guess. Identical evidence and options are answered from the saved answer, with no request.

Examples:

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

pick = ChoiceModel(ScriptedDecisionModel({'response': {'left': 0.8, 'right': 0.2}}))
decision = pick.choose(
    {'hero': 'at the right wall'},
    {'left': 'the hero should step left', 'right': 'the hero should step right'},
    question='Where should the hero go?',
)
assert decision.choice == 'left' and decision.margin > 0.5

Methods:

  • 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.

  • choose_async –

    Pick one of the options for the evidence, with await.

  • choose –

    Pick one of the options for the evidence, waiting for the answer.

Attributes:

Source code in xnano/ai/models/decisions.py
def __init__(self, *arguments: Any, **keywords: Any) -> None:
    super().__init__(*arguments, **keywords)
    self._is_reusing_answers = keywords.get('cache', True)
    self._saved = _SavedAnswers()

is_decision_model property

is_decision_model: bool

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

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)

choose_async

choose_async(evidence: object, options: Options, *, question: str | None = None, no_change: str | None = 'nothing needs to change now') -> Coroutine[Any, Any, Decision]

Pick one of the options for the evidence, with await.

The evidence is read when this is called, so the model judges the canvas as it was then, and the options are checked then too; await the result for the decision.

Parameters:

  • evidence (object) –

    What to decide about: a context, canvas or placement, or a mapping of them with the facts your program knows; see Evidence.

  • options (Options) –

    The labels to pick from, with what each means; see Options.

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

    What is being decided, such as 'What should the hero do now?'.

  • no_change (str | None, default: 'nothing needs to change now' ) –

    What the no_change option means, or None to offer only your options.

Returns:

Raises:

  • ValueError –

    No option was given besides no_change, or more than 255.

  • TerminalError –

    The model could not be reached (ai.model), when awaited.

Source code in xnano/ai/models/decisions.py
def choose_async(
    self,
    evidence: object,
    options: Options,
    *,
    question: str | None = None,
    no_change: str | None = 'nothing needs to change now',
) -> Coroutine[Any, Any, Decision]:
    """
    Pick one of the options for the evidence, with ``await``.

    The evidence is read when this is called, so the model judges the canvas as it was
    then, and the options are checked then too; await the result for the decision.

    Args:
        evidence: What to decide about: a context, canvas or placement, or a mapping of
            them with the facts your program knows; see [`Evidence`][xnano.ai.Evidence].
        options: The labels to pick from, with what each means; see
            [`Options`][xnano.ai.models.decisions.Options].
        question: What is being decided, such as ``'What should the hero do now?'``.
        no_change: What the ``no_change`` option means, or ``None`` to offer only your
            options.

    Returns:
        A coroutine that gives the [`Decision`][xnano.ai.models.decisions.Decision].

    Raises:
        ValueError: No option was given besides ``no_change``, or more than 255.
        TerminalError: The model could not be reached (``ai.model``), when awaited.
    """
    offered = _offered(options, no_change)
    return self._choose(snapshot(evidence), offered, question)

choose

choose(evidence: object, options: Options, *, question: str | None = None, no_change: str | None = 'nothing needs to change now') -> Decision

Pick one of the options for the evidence, waiting for the answer.

The same as choose_async, for code that does not await. A callable value of the option picked is called on the calling thread, so it may change the canvas.

Source code in xnano/ai/models/decisions.py
def choose(
    self,
    evidence: object,
    options: Options,
    *,
    question: str | None = None,
    no_change: str | None = 'nothing needs to change now',
) -> Decision:
    """
    Pick one of the options for the evidence, waiting for the answer.

    The same as [`choose_async`][xnano.ai.models.decisions.ChoiceModel.choose_async], for code that does not
    await. A callable value of the option picked is called on the calling thread, so it
    may change the canvas.
    """
    offered = _offered(options, no_change)
    label, probabilities, confidence = _run_blocking(
        self._pick(snapshot(evidence), offered, question), 'choose'
    )
    value = _resolve_blocking(offered[label][1], label, 'choose')
    return Decision(
        choice=label, value=value, probabilities=probabilities, confidence=confidence
    )

JudgeModel

JudgeModel(*arguments: Any, **keywords: Any)

Bases: _AskingModel

Answer yes/no questions, and place evidence on a rubric.

On a decision model each answer comes with the probability of a yes, and threshold sets how sure a yes has to be. Ask one question per thing you want to know, with "yes" meaning that it is true; several questions about the same evidence go in one request with ask_many.

Examples:

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

judge = JudgeModel(ScriptedDecisionModel({'answer': 0.9}))
verdict = judge.ask('Ada typed: "Ada"', 'Has the user finished typing their name?')
assert verdict.answer and verdict.probability > 0.8

Methods:

  • 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.

  • ask_async –

    Answer a yes/no question about the evidence, with await.

  • ask –

    Answer a yes/no question about the evidence, waiting for the answer.

  • ask_many_async –

    Answer several yes/no questions about the same evidence in one request, with await.

  • ask_many –

    Answer several yes/no questions about the same evidence in one request, waiting.

  • score_async –

    Place the evidence on a rubric of levels, with await.

  • score –

    Place the evidence on a rubric of levels, waiting for the answer.

Attributes:

Source code in xnano/ai/models/decisions.py
def __init__(self, *arguments: Any, **keywords: Any) -> None:
    super().__init__(*arguments, **keywords)
    self._is_reusing_answers = keywords.get('cache', True)
    self._saved = _SavedAnswers()

is_decision_model property

is_decision_model: bool

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

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)

ask_async

ask_async(evidence: object, question: str, *, threshold: float = 0.5, yes: str | None = None, no: str | None = None) -> Coroutine[Any, Any, Verdict]

Answer a yes/no question about the evidence, with await.

The evidence is read when this is called; await the result for the verdict.

Parameters:

  • evidence (object) –

    What the question is about; see Evidence.

  • question (str) –

    The question, such as 'Is the board full?'.

  • threshold (float, default: 0.5 ) –

    How likely a yes has to be to count, on a decision model.

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

    What a yes means, when the question alone leaves it open.

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

    What a no means.

Returns:

Raises:

  • ValueError –

    threshold is not from 0 to 1.

  • TerminalError –

    The model could not be reached (ai.model), when awaited.

Source code in xnano/ai/models/decisions.py
def ask_async(
    self,
    evidence: object,
    question: str,
    *,
    threshold: float = 0.5,
    yes: str | None = None,
    no: str | None = None,
) -> Coroutine[Any, Any, Verdict]:
    """
    Answer a yes/no question about the evidence, with ``await``.

    The evidence is read when this is called; await the result for the verdict.

    Args:
        evidence: What the question is about; see [`Evidence`][xnano.ai.Evidence].
        question: The question, such as ``'Is the board full?'``.
        threshold: How likely a yes has to be to count, on a decision model.
        yes: What a yes means, when the question alone leaves it open.
        no: What a no means.

    Returns:
        A coroutine that gives the [`Verdict`][xnano.ai.models.decisions.Verdict].

    Raises:
        ValueError: ``threshold`` is not from 0 to 1.
        TerminalError: The model could not be reached (``ai.model``), when awaited.
    """
    _check_threshold(threshold)
    return self._ask_one(snapshot(evidence), (question, yes, no), threshold)

ask

ask(evidence: object, question: str, *, threshold: float = 0.5, yes: str | None = None, no: str | None = None) -> Verdict

Answer a yes/no question about the evidence, waiting for the answer.

The same as ask_async, for code that does not await.

Source code in xnano/ai/models/decisions.py
def ask(
    self,
    evidence: object,
    question: str,
    *,
    threshold: float = 0.5,
    yes: str | None = None,
    no: str | None = None,
) -> Verdict:
    """
    Answer a yes/no question about the evidence, waiting for the answer.

    The same as [`ask_async`][xnano.ai.models.decisions.JudgeModel.ask_async], for code that does not await.
    """
    return _run_blocking(
        self.ask_async(evidence, question, threshold=threshold, yes=yes, no=no), 'ask'
    )

ask_many_async

ask_many_async(evidence: object, questions: Sequence[str] | Mapping[str, str], *, threshold: float = 0.5) -> Coroutine[Any, Any, dict[str, Verdict]]

Answer several yes/no questions about the same evidence in one request, with await.

The evidence is read when this is called; await the result for the verdicts.

Parameters:

  • evidence (object) –

    What the questions are about; see Evidence.

  • questions (Sequence[str] | Mapping[str, str]) –

    The questions, or a mapping from a name of your own to each question.

  • threshold (float, default: 0.5 ) –

    How likely a yes has to be to count, on a decision model.

Returns:

Raises:

  • ValueError –

    No question was given, a name is not a Python identifier, or threshold is not from 0 to 1.

  • TerminalError –

    The model could not be reached (ai.model).

Source code in xnano/ai/models/decisions.py
def ask_many_async(
    self,
    evidence: object,
    questions: Sequence[str] | Mapping[str, str],
    *,
    threshold: float = 0.5,
) -> Coroutine[Any, Any, dict[str, Verdict]]:
    """
    Answer several yes/no questions about the same evidence in one request, with ``await``.

    The evidence is read when this is called; await the result for the verdicts.

    Args:
        evidence: What the questions are about; see [`Evidence`][xnano.ai.Evidence].
        questions: The questions, or a mapping from a name of your own to each question.
        threshold: How likely a yes has to be to count, on a decision model.

    Returns:
        A coroutine that gives each [`Verdict`][xnano.ai.models.decisions.Verdict], by its question, or by
        its name when a mapping was given.

    Raises:
        ValueError: No question was given, a name is not a Python identifier, or
            ``threshold`` is not from 0 to 1.
        TerminalError: The model could not be reached (``ai.model``).
    """
    _check_threshold(threshold)
    if isinstance(questions, str):
        raise TypeError(
            f'ask_many() takes a list of questions, but got the single string '
            f'{questions!r}. Use ask() for one question.'
        )
    if isinstance(questions, Mapping):
        named = {str(name): question for name, question in questions.items()}
        for name in named:
            if not name.isidentifier():
                raise ValueError(
                    f'The name {name!r} of a question must be a Python identifier, such '
                    f"as 'is_full', because it names the answer."
                )
    else:
        named = {
            f'question_{index}': question
            for index, question in enumerate(questions, 1)
        }
    if not named:
        raise ValueError('ask_many() needs at least one question.')
    return self._ask_several(
        snapshot(evidence), named, threshold, is_named=isinstance(questions, Mapping)
    )

ask_many

ask_many(evidence: object, questions: Sequence[str] | Mapping[str, str], *, threshold: float = 0.5) -> dict[str, Verdict]

Answer several yes/no questions about the same evidence in one request, waiting.

The same as ask_many_async, for code that does not await.

Source code in xnano/ai/models/decisions.py
def ask_many(
    self,
    evidence: object,
    questions: Sequence[str] | Mapping[str, str],
    *,
    threshold: float = 0.5,
) -> dict[str, Verdict]:
    """
    Answer several yes/no questions about the same evidence in one request, waiting.

    The same as [`ask_many_async`][xnano.ai.models.decisions.JudgeModel.ask_many_async], for code that does
    not await.
    """
    return _run_blocking(
        self.ask_many_async(evidence, questions, threshold=threshold),
        'ask_many',
    )

score_async

score_async(evidence: object, levels: Sequence[str], *, question: str | None = None) -> Coroutine[Any, Any, Score]

Place the evidence on a rubric of levels, with await.

The evidence is read when this is called; await the result for the score.

Describe each level as a situation ('two or three items on the screen'), not as a degree ('somewhat busy'). A rubric is the least reliable kind of answer on current decision models: for anything that matters, ask a yes/no or pick one option instead.

Parameters:

  • evidence (object) –

    What to score; see Evidence.

  • levels (Sequence[str]) –

    The levels in order, from lowest to highest; at least two.

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

    What the rubric measures, such as 'How busy is the screen?'.

Returns:

Raises:

  • ValueError –

    Fewer than two levels were given.

  • TerminalError –

    The model could not be reached (ai.model), when awaited.

Source code in xnano/ai/models/decisions.py
def score_async(
    self, evidence: object, levels: Sequence[str], *, question: str | None = None
) -> Coroutine[Any, Any, Score]:
    """
    Place the evidence on a rubric of levels, with ``await``.

    The evidence is read when this is called; await the result for the score.

    Describe each level as a situation (``'two or three items on the screen'``), not as a
    degree (``'somewhat busy'``). A rubric is the least reliable kind of answer on current
    decision models: for anything that matters, ask a yes/no or pick one option instead.

    Args:
        evidence: What to score; see [`Evidence`][xnano.ai.Evidence].
        levels: The levels in order, from lowest to highest; at least two.
        question: What the rubric measures, such as ``'How busy is the screen?'``.

    Returns:
        A coroutine that gives the [`Score`][xnano.ai.models.decisions.Score].

    Raises:
        ValueError: Fewer than two levels were given.
        TerminalError: The model could not be reached (``ai.model``), when awaited.
    """
    if isinstance(levels, str) or len(levels) < 2:
        raise ValueError(
            f'score() takes at least two levels, from lowest to highest, such as '
            f"['empty', 'sparse', 'busy'], but got {levels!r}."
        )
    labels = [str(level) for level in levels]
    return self._score(
        snapshot(evidence), labels, question or 'Which level describes the evidence?'
    )

score

score(evidence: object, levels: Sequence[str], *, question: str | None = None) -> Score

Place the evidence on a rubric of levels, waiting for the answer.

The same as score_async, for code that does not await.

Source code in xnano/ai/models/decisions.py
def score(
    self, evidence: object, levels: Sequence[str], *, question: str | None = None
) -> Score:
    """
    Place the evidence on a rubric of levels, waiting for the answer.

    The same as [`score_async`][xnano.ai.models.decisions.JudgeModel.score_async], for code that does not
    await.
    """
    return _run_blocking(
        self.score_async(evidence, levels, question=question), 'score'
    )

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:

  • 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.

  • 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.

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.

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)

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')

StateModel

StateModel(state_type: type[StateT], model: Model | KnownModelName | str | None = None, *, invariants: Sequence[Invariant] = (), 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, Generic[StateT]

Keep a small state up to date as things happen.

The state is a dataclass or a Pydantic model. On a decision model, the fields with a few values (bool and Literal) are decided: when the combinations of them are 255 or fewer, the model picks the whole next state among the ones that keep every invariant, so fields that depend on each other change together; with more, each field is asked on its own among the values that keep the invariants. Other fields keep their values. On a language model, the model writes the fields that change and why, and an answer that breaks an invariant is sent back to be fixed.

Parameters:

  • state_type (type[StateT]) –

    The dataclass or Pydantic model of the state.

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

    The model to ask.

  • invariants (Sequence[Invariant], default: () ) –

    Rules every state must keep, as functions of the state that return whether they hold.

  • 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 an answer that breaks an invariant 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.

Examples:

from dataclasses import dataclass
from typing import Literal

from xnano.ai.models.state import StateModel
from xnano.ai.testing import ScriptedDecisionModel


@dataclass
class Goblin:
    mood: Literal['calm', 'wary', 'angry'] = 'calm'
    is_hostile: bool = False


moods = StateModel(
    Goblin,
    ScriptedDecisionModel({'response': 'mood=angry, is_hostile=true'}),
    invariants=[lambda goblin: goblin.mood == 'angry' or not goblin.is_hostile],
)
transition = moods.update(Goblin(), 'The hero stole its lunch.')
assert transition.after == Goblin(mood='angry', is_hostile=True)
assert transition.changes['mood'] == ('calm', 'angry')

Create the state model; nothing is sent until the first update.

Raises:

  • TypeError –

    state_type is not a dataclass or a Pydantic model, or an invariant is not a function.

Methods:

  • 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.

  • update_async –

    Work out the state after what the evidence says happened, with await.

  • update –

    Work out the state after what the evidence says happened, waiting for the answer.

Attributes:

Source code in xnano/ai/models/state.py
def __init__(
    self,
    state_type: type[StateT],
    model: Model | KnownModelName | str | None = None,
    *,
    invariants: Sequence[Invariant] = (),
    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 state model; nothing is sent until the first update.

    Raises:
        TypeError: ``state_type`` is not a dataclass or a Pydantic model, or an invariant
            is not a function.
    """
    self._fields = _field_types(state_type)
    for rule in invariants:
        if not callable(rule):
            raise TypeError(
                f'An invariant is a function of the state that returns whether it holds, '
                f'such as lambda state: state.health >= 0, but got {rule!r}.'
            )
    super().__init__(
        model,
        instructions=instructions,
        model_settings=model_settings,
        capabilities=capabilities,
        retries=retries,
        usage_limits=usage_limits,
        thinking=thinking,
        cache=cache,
    )
    self.state_type = state_type
    self.invariants = tuple(invariants)
    self._retries = retries

is_decision_model property

is_decision_model: bool

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

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)

update_async

update_async(current: StateT, evidence: object) -> Coroutine[Any, Any, StateTransition[StateT]]

Work out the state after what the evidence says happened, with await.

The evidence is read, and the current state checked, when this is called; await the result for the transition.

Parameters:

  • current (StateT) –

    The state now.

  • evidence (object) –

    What happened, such as 'The hero stole its lunch.' or the hook's context; see Evidence.

Returns:

Raises:

  • ValueError –

    current breaks an invariant, or on a decision model the state has no bool or Literal field to decide.

  • TerminalError –

    The model could not be reached (ai.model), or a language model kept breaking an invariant (ai.generation), when awaited.

Source code in xnano/ai/models/state.py
def update_async(
    self, current: StateT, evidence: object
) -> Coroutine[Any, Any, StateTransition[StateT]]:
    """
    Work out the state after what the evidence says happened, with ``await``.

    The evidence is read, and the current state checked, when this is called; await the
    result for the transition.

    Args:
        current: The state now.
        evidence: What happened, such as ``'The hero stole its lunch.'`` or the hook's
            context; see [`Evidence`][xnano.ai.Evidence].

    Returns:
        A coroutine that gives the [`StateTransition`][xnano.ai.models.state.StateTransition].

    Raises:
        ValueError: ``current`` breaks an invariant, or on a decision model the state has
            no ``bool`` or ``Literal`` field to decide.
        TerminalError: The model could not be reached (``ai.model``), or a language model
            kept breaking an invariant (``ai.generation``), when awaited.
    """
    if not self._keeps_invariants(current):
        raise ValueError(
            f'The current state {current!r} breaks the invariants '
            f'{", ".join(self._broken_invariants(current))}, so no update can start from '
            f'it. Fix the state, or the invariants.'
        )
    if self.is_decision_model:
        return self._decide(current, snapshot(evidence))
    return self._patch(current, snapshot(evidence))

update

update(current: StateT, evidence: object) -> StateTransition[StateT]

Work out the state after what the evidence says happened, waiting for the answer.

The same as update_async, for code that does not await.

Source code in xnano/ai/models/state.py
def update(self, current: StateT, evidence: object) -> StateTransition[StateT]:
    """
    Work out the state after what the evidence says happened, waiting for the answer.

    The same as [`update_async`][xnano.ai.models.state.StateModel.update_async], for code that does not
    await.
    """
    return _run_blocking(self.update_async(current, evidence), 'update')

TextModel

TextModel(model: Model | KnownModelName | str | None = None, *, style: str | None = None, max_sentences: int | 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

Write prose for the canvas: a description, a narration, a line of dialogue.

generate returns the whole text; stream gives it piece by piece as the model writes it, which stream_into shows in a placement as it arrives.

Parameters:

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

    The language model to ask.

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

    How the text should read, such as 'wry, second person'.

  • max_sentences (int | None, default: None ) –

    The most sentences an answer keeps; a longer answer is cut after them.

  • 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 an empty answer is asked again.

  • 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.

Examples:

from xnano.ai.models.text import TextModel
from xnano.ai.testing import scripted_model

writer = TextModel(scripted_model('A door. A key. A choice.').model, max_sentences=2)
assert writer.generate('Describe the room.') == 'A door. A key.'

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

Raises:

  • ValueError –

    max_sentences is not a whole number of 1 or more.

Methods:

  • 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.

  • generate_async –

    Write the text asked for, with await.

  • generate –

    Write the text asked for, waiting for the whole answer.

  • stream_async –

    Write the text asked for, giving each new piece as the model writes it, with

  • stream –

    Write the text asked for, giving each piece as it is written, for code that does not

Attributes:

Source code in xnano/ai/models/text.py
def __init__(
    self,
    model: Model | KnownModelName | str | None = None,
    *,
    style: str | None = None,
    max_sentences: int | 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 text model; nothing is sent until the first call.

    Raises:
        ValueError: ``max_sentences`` is not a whole number of 1 or more.
    """
    if max_sentences is not None and (
        isinstance(max_sentences, bool)
        or not isinstance(max_sentences, int)
        or max_sentences < 1
    ):
        raise ValueError(
            f'max_sentences must be a whole number of 1 or more, or None, but was '
            f'{max_sentences!r}.'
        )
    parts = [instructions or '']
    if style:
        parts.append(f'Write in this style: {style}.')
    if max_sentences is not None:
        parts.append(f'Write at most {max_sentences} sentences.')
    super().__init__(
        model,
        instructions=' '.join(part for part in parts if part) or None,
        model_settings=model_settings,
        capabilities=capabilities,
        retries=retries,
        usage_limits=usage_limits,
        thinking=thinking,
        cache=cache,
    )
    self.style = style
    self.max_sentences = max_sentences
    self._retries = retries

is_decision_model property

is_decision_model: bool

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

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)

generate_async

generate_async(request: str, evidence: object = None) -> Coroutine[Any, Any, str]

Write the text asked for, with await.

The evidence is read when this is called; await the result for the text.

Parameters:

  • request (str) –

    What to write, such as 'Describe the room the hero just entered.'.

  • evidence (object, default: None ) –

    What the text is about, such as the hook's context; see Evidence. None sends the request alone.

Returns:

  • Coroutine[Any, Any, str] –

    A coroutine that gives the text, cut after max_sentences sentences.

Raises:

  • TerminalError –

    The model could not be reached (ai.model), or wrote nothing, even when asked again (ai.generation), when awaited.

Source code in xnano/ai/models/text.py
def generate_async(
    self, request: str, evidence: object = None
) -> Coroutine[Any, Any, str]:
    """
    Write the text asked for, with ``await``.

    The evidence is read when this is called; await the result for the text.

    Args:
        request: What to write, such as ``'Describe the room the hero just entered.'``.
        evidence: What the text is about, such as the hook's context; see
            [`Evidence`][xnano.ai.Evidence]. ``None`` sends the request alone.

    Returns:
        A coroutine that gives the text, cut after ``max_sentences`` sentences.

    Raises:
        TerminalError: The model could not be reached (``ai.model``), or wrote nothing,
            even when asked again (``ai.generation``), when awaited.
    """
    return self._generate(self._prompt(request, snapshot(evidence)))

generate

generate(request: str, evidence: object = None) -> str

Write the text asked for, waiting for the whole answer.

The same as generate_async, for code that does not await.

Source code in xnano/ai/models/text.py
def generate(self, request: str, evidence: object = None) -> str:
    """
    Write the text asked for, waiting for the whole answer.

    The same as [`generate_async`][xnano.ai.models.text.TextModel.generate_async], for code that does
    not await.
    """
    return _run_blocking(self.generate_async(request, evidence), 'generate')

stream_async

stream_async(request: str, evidence: object = None) -> AsyncIterator[str]

Write the text asked for, giving each new piece as the model writes it, with async for.

The evidence is read when this is called.

Parameters:

  • request (str) –

    What to write.

  • evidence (object, default: None ) –

    What the text is about; see Evidence.

Yields:

  • AsyncIterator[str] –

    The pieces of the text, in order: joined, they are the whole text.

Raises:

Examples:

import asyncio

from xnano.ai.models.text import TextModel
from xnano.ai.testing import scripted_model

writer = TextModel(scripted_model('Once upon a time.').model)


async def main() -> str:
    return ''.join([piece async for piece in writer.stream_async('Begin.')])


assert asyncio.run(main()) == 'Once upon a time.'
Source code in xnano/ai/models/text.py
def stream_async(self, request: str, evidence: object = None) -> AsyncIterator[str]:
    """
    Write the text asked for, giving each new piece as the model writes it, with
    ``async for``.

    The evidence is read when this is called.

    Args:
        request: What to write.
        evidence: What the text is about; see [`Evidence`][xnano.ai.Evidence].

    Yields:
        The pieces of the text, in order: joined, they are the whole text.

    Raises:
        TerminalError: The model could not be reached (``ai.model``).

    Examples:
        ```python
        import asyncio

        from xnano.ai.models.text import TextModel
        from xnano.ai.testing import scripted_model

        writer = TextModel(scripted_model('Once upon a time.').model)


        async def main() -> str:
            return ''.join([piece async for piece in writer.stream_async('Begin.')])


        assert asyncio.run(main()) == 'Once upon a time.'
        ```
    """
    self._require_model('stream')
    return self._stream(self._prompt(request, snapshot(evidence)))

stream

stream(request: str, evidence: object = None) -> Iterator[str]

Write the text asked for, giving each piece as it is written, for code that does not await.

The same as stream_async. Stopping the loop early cancels the request.

Source code in xnano/ai/models/text.py
def stream(self, request: str, evidence: object = None) -> Iterator[str]:
    """
    Write the text asked for, giving each piece as it is written, for code that does not
    await.

    The same as [`stream_async`][xnano.ai.models.text.TextModel.stream_async]. Stopping the loop
    early cancels the request.
    """
    return _blocking_pieces(self.stream_async(request, evidence), 'stream')

is_decision_model

is_decision_model(model: Model | KnownModelName | str | None) -> bool

Whether a model answers typed questions with probabilities instead of writing text.

A decision model (TypeSafe, OpenAI Decisions, System One) is sent the evidence as JSON and answers each question with a probability or a distribution, which task models report as probabilities and margin. A language model writes its answer instead. A FallbackModel counts as the first model it tries.

Parameters:

  • model (Model | KnownModelName | str | None) –

    A pydantic-ai Model, a model name such as 'typesafe:jev-1.14.0', or None.

Examples:

from xnano.ai.models import is_decision_model

assert is_decision_model('typesafe:jev-1.14.0')
assert not is_decision_model('openrouter:anthropic/claude-sonnet-5-5')
Source code in xnano/ai/models/__init__.py
def is_decision_model(model: Model | KnownModelName | str | None) -> bool:
    """
    Whether a model answers typed questions with probabilities instead of writing text.

    A decision model (TypeSafe, OpenAI Decisions, System One) is sent the evidence as JSON and
    answers each question with a probability or a distribution, which task models report as
    ``probabilities`` and ``margin``. A language model writes its answer instead. A
    ``FallbackModel`` counts as the first model it tries.

    Args:
        model: A pydantic-ai ``Model``, a model name such as ``'typesafe:jev-1.14.0'``, or
            ``None``.

    Examples:
        ```python
        from xnano.ai.models import is_decision_model

        assert is_decision_model('typesafe:jev-1.14.0')
        assert not is_decision_model('openrouter:anthropic/claude-sonnet-5-5')
        ```
    """
    if model is None:
        return False
    if isinstance(model, str):
        return model.startswith(_DECISION_PROVIDERS)
    if isinstance(model, FallbackModel):
        return bool(model.models) and is_decision_model(model.models[0])
    if isinstance(model, WrapperModel):
        return is_decision_model(model.wrapped)
    return isinstance(model, DecisionModel)

run_to_completion

run_to_completion(awaitable: Awaitable[ResultT]) -> ResultT

Run an awaitable from code that does not await, and return its result.

It runs on an event loop of xnano's own on a background thread, which stays open between calls, so model clients that keep connections open work across calls. Every blocking method of a task model (choose, generate, ...) runs its _async twin this way.

Raises:

  • TerminalError –

    Called inside a running event loop, which waiting would freeze (use await instead), or from a hook of a canvas that runs by itself, which waiting would freeze on the screen (use an async def hook or background()).

Examples:

import asyncio

from xnano.ai.models import run_to_completion


async def answer() -> int:
    await asyncio.sleep(0)
    return 42


assert run_to_completion(answer()) == 42
Source code in xnano/ai/models/__init__.py
def run_to_completion(awaitable: Awaitable[ResultT]) -> ResultT:
    """
    Run an awaitable from code that does not await, and return its result.

    It runs on an event loop of xnano's own on a background thread, which stays open between
    calls, so model clients that keep connections open work across calls. Every blocking method
    of a task model (``choose``, ``generate``, ...) runs its ``_async`` twin this way.

    Raises:
        TerminalError: Called inside a running event loop, which waiting would freeze (use
            ``await`` instead), or from a hook of a canvas that runs by itself, which waiting
            would freeze on the screen (use an ``async def`` hook or ``background()``).

    Examples:
        ```python
        import asyncio

        from xnano.ai.models import run_to_completion


        async def answer() -> int:
            await asyncio.sleep(0)
            return 42


        assert run_to_completion(answer()) == 42
        ```
    """
    return _run_blocking(awaitable, None)