Skip to content

xnano.ai

xnano.ai

xnano.ai

Language models, decision models and agents that work on a canvas: task models that decide what a widget does, judge what is on the screen, keep state, and write text, pixel art, components and melodies.

Each task model lives in a module of xnano.ai.models, named for what it makes, and is exported from xnano.ai too, so from xnano.ai import ArtModel works:

Module Models
xnano.ai.models.decisions ChoiceModel and JudgeModel: pick an option, or judge a claim
xnano.ai.models.state StateModel: move a program's state from one value to the next
xnano.ai.models.text TextModel: write and stream text into a placement
xnano.ai.models.art ArtModel: generate, edit and animate pixel art
xnano.ai.models.components ComponentModel: write a component as a program
xnano.ai.models.music MusicModel: write melodies

Each one owns one pydantic-ai agent. Its methods take what is on the canvas as evidence (a hook's Context, a canvas, a placement, or a mapping of them with the facts the program knows) and return xnano values. Every method that asks a model has two spellings: choose() waits for the answer, and choose_async() is awaited. They share the errors and reports of a generation, the evidence they read, and the plugins that run them from hooks, all defined here; xnano.ai.capabilities gives an agent the canvas.

Decision models ('typesafe:jev-1.14.0') answer typed questions with probabilities in a fraction of a second, which suits what happens on a key press; language models ('openrouter:anthropic/claude-sonnet-5-5') write text and drawings. Install with pip install "xnano[ai]"; it needs Python 3.11 or newer.

xnano.ai.testing has models that answer from a script, for tests and for trying a program without credentials.

Examples:

import xnano
from xnano.ai import ChoiceModel
from xnano.ai.testing import ScriptedDecisionModel
from xnano.events import Event

pick = ChoiceModel(ScriptedDecisionModel({'response': 'wave'}))

with xnano.new(width=20, height=2) as canvas:
    hero = canvas.screen.write('hero')

    @hero.hook(on='key', keys='enter')
    def react(context: xnano.Context) -> None:
        decision = pick.choose(context, {'wave': 'greet the player', 'hide': 'run away'})
        hero.text = f'hero: {decision.choice}'

    canvas.push(Event.key_press('enter'))
    canvas.clock.step()
    assert canvas.screen.render().splitlines()[0] == 'hero: wave'

Modules:

Classes:

  • BackgroundRun –

    One call running in the background of a canvas, such as a model's answer.

  • BackgroundRuns –

    The background runs of one canvas: start calls, and read their answers when they land.

  • Critique –

    What a critic saw in a piece: a score, and each problem it would fix.

  • GenerationError –

    Raised when no answer of the model could be made into what was asked for.

  • GenerationReport –

    How a generation went: the answers sent back to be fixed, and the repairs made.

  • Observation –

    The canvas, or a part of it, as a model reads it.

  • TaskModel –

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

  • Animation –

    Frames of pixel art shown one after another: what ArtModel.animate makes.

  • ArtModel –

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

  • ArtPatch –

    A change to pixel art: the runs of pixels it sets, and any colours it adds.

  • ArtText –

    Pixel art as a model writes it: rows of one letter per pixel, and a palette with roles.

  • PaletteColor –

    One colour of a palette, and what it is for.

  • PixelRun –

    Pixels set in a row, from a column to the right: one letter of the palette per pixel.

  • Component –

    A widget a model wrote: a small program that draws on a canvas of its own size.

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

  • Decision –

    The option a ChoiceModel picked, and how sure it was.

  • JudgeModel –

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

  • Score –

    The level of a rubric a JudgeModel placed the evidence at.

  • Verdict –

    The answer of a JudgeModel to a yes/no question.

  • MusicModel –

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

  • StateModel –

    Keep a small state up to date as things happen.

  • StateTransition –

    How a StateModel changed a state.

  • TextModel –

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

Functions:

  • background –

    The background runs of a canvas, to start slow calls from a plain hook.

  • observe –

    Read a canvas, a placement, a hook's context, a frame or a piece of art as a model would.

  • decide –

    Let a choice model decide what a placement does, when something happens to it.

  • watch –

    Let a judge model keep answering a yes/no question about a placement.

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

  • stream_into –

    Show text in a placement as its pieces arrive, for code that does not await.

  • stream_into_async –

    Show text in a placement as its pieces arrive, and return the whole text.

Attributes:

  • Evidence –

    What a decision or judgement is about.

  • ArtSize (TypeAlias) –

    The size of art in pixels: a number such as 16, a share of the active canvas such as

  • ArtStrategy –

    How the model writes the art: a small 'program' of drawing calls (rectangles, ellipses,

  • ColorRole –

    What a colour of a palette is for: 'outline', 'base', 'shadow', 'highlight', 'accent', 'skin' or 'detail'.

  • EditMode –

    How an edit is written: a 'patch' of the pixels that change, a 'redraw' of all of them, or 'auto' for the model to choose.

  • Options –

    The options of a decision: labels, a mapping from label to what it means, or a mapping from

  • Meter (TypeAlias) –

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

ArtSize module-attribute

ArtSize: TypeAlias = 'int | Percentage | str | tuple[int | None, int | None] | None'

The size of art in pixels: a number such as 16, a share of the active canvas such as '50%' (a cell is one pixel wide and two tall), an expression such as ParentWidth - 4, a (low, high) range the model picks within, or None for any size up to 32.

ArtStrategy module-attribute

ArtStrategy = Literal['program', 'svg']

How the model writes the art: a small 'program' of drawing calls (rectangles, ellipses, lines, polygons, fills, mirrors and an outline), or an 'svg' drawing sampled onto the pixels.

ColorRole module-attribute

ColorRole = Literal['outline', 'base', 'shadow', 'highlight', 'accent', 'skin', 'detail']

What a colour of a palette is for: 'outline', 'base', 'shadow', 'highlight', 'accent', 'skin' or 'detail'.

EditMode module-attribute

EditMode = Literal['auto', 'patch', 'redraw']

How an edit is written: a 'patch' of the pixels that change, a 'redraw' of all of them, or 'auto' for the model to choose.

Options module-attribute

Options = Sequence[str] | Mapping[str, 'str | Choice[Any]']

The options of a decision: labels, a mapping from label to what it means, or a mapping from label to a pydantic-ai Choice whose value is what the label stands for. A callable value is called when its option is picked, and the decision's value is what it returned.

BackgroundRun

BackgroundRun(name: str, identifier: str)

Bases: Generic[ResultT]

One call running in the background of a canvas, such as a model's answer.

BackgroundRuns.start returns one. When it finishes, the canvas hears the custom event event_name, and a hook on that event reads the answer with BackgroundRuns.result. A run that was replaced or cancelled sends no event.

Attributes:

  • name –

    The name it was started with, such as 'move'.

  • event_name –

    The custom event its finishing sends: 'ai.' and the name.

  • is_finished –

    Whether it finished, with a result or an error.

  • is_cancelled –

    Whether it was cancelled or replaced before it finished.

  • error (BaseException | None) –

    The error the call raised, or None.

Track a run. Use BackgroundRuns.start instead of calling this.

Methods:

  • cancel –

    Cancel the run if it has not finished; it then sends no event. Safe from any thread.

Source code in xnano/ai/_background.py
def __init__(self, name: str, identifier: str) -> None:
    """Track a run. Use ``BackgroundRuns.start`` instead of calling this."""
    self.name = name
    self.event_name = f'ai.{name}'
    self._identifier = identifier
    self._result: ResultT | None = None
    self.error: BaseException | None = None
    self.is_finished = False
    self.is_cancelled = False
    self._task: asyncio.Task[None] | None = None

result property

result: ResultT

What the call returned.

Raises:

cancel

cancel() -> None

Cancel the run if it has not finished; it then sends no event. Safe from any thread.

Source code in xnano/ai/_background.py
def cancel(self) -> None:
    """Cancel the run if it has not finished; it then sends no event. Safe from any thread."""
    if self.is_finished:
        return
    self.is_cancelled = True
    task = self._task
    if task is None:
        return
    loop = task.get_loop()
    if loop.is_closed():
        return
    if running_loop() is loop:
        task.cancel()
    else:
        loop.call_soon_threadsafe(task.cancel)

BackgroundRuns

BackgroundRuns(canvas: Canvas[object, object])

The background runs of one canvas: start calls, and read their answers when they land.

Get it with background. A run starts on the event loop the canvas was created or opened in, or on xnano's own background loop. On a canvas with a manual clock and no event loop (a test or a script), the call runs at once, and its event is heard in the same step() when a hook started it, or at the next one otherwise, so the program stays the same from run to run.

Keep the runs of canvas. Use background(canvas) instead of calling this.

Methods:

  • start –

    Start a call in the background; the canvas hears 'ai.<name>' when it finishes.

  • run –

    The run whose finishing event a hook heard.

  • result –

    What the run whose event a hook heard returned.

Source code in xnano/ai/_background.py
def __init__(self, canvas: Canvas[object, object]) -> None:
    """Keep the runs of ``canvas``. Use ``background(canvas)`` instead of calling this."""
    self._canvas = canvas
    self._runs: dict[str, BackgroundRun[Any]] = {}
    self._unfinished: dict[str, list[BackgroundRun[Any]]] = {}
    self._counter = itertools.count(1)
    self._lock = threading.Lock()

start

start(call: Awaitable[ResultT], *, name: str, if_running: IfRunning = 'replace') -> BackgroundRun[ResultT]

Start a call in the background; the canvas hears 'ai.<name>' when it finishes.

Parameters:

  • call (Awaitable[ResultT]) –

    What to run, such as pick.choose_async(context, options).

  • name (str) –

    The name of the run, such as 'move': letters, digits and underscores, with dots between parts. Its event is 'ai.' and the name.

  • if_running (IfRunning, default: 'replace' ) –

    What happens when a run of the same name has not finished: 'replace' cancels it, so the latest call wins; 'ignore' keeps it and drops this call; 'queue' runs this one after it; 'overlap' runs both.

Returns:

Raises:

  • ValueError –

    name is not a name, or if_running is not one of its words.

  • TerminalClosedError –

    The canvas is closed.

Examples:

import xnano
from xnano.ai.models.decisions import ChoiceModel
from xnano.ai import background
from xnano.ai.testing import ScriptedDecisionModel
from xnano.events import Event

pick = ChoiceModel(ScriptedDecisionModel({'response': 'jump'}))

with xnano.new(width=20, height=1) as canvas:
    runs = background(canvas)
    hero = canvas.screen.write('hero')

    @canvas.hook(on='key', keys='enter')
    def ask(context: xnano.Context) -> None:
        runs.start(pick.choose_async(context, ['jump', 'duck']), name='move')

    @canvas.hook(on='ai.move')
    def moved(context: xnano.Context) -> None:
        hero.text = f'hero: {runs.result(context).choice}'

    canvas.push(Event.key_press('enter'))
    canvas.clock.step()
    assert canvas.screen.render() == 'hero: jump'
Source code in xnano/ai/_background.py
def start(
    self,
    call: Awaitable[ResultT],
    *,
    name: str,
    if_running: IfRunning = 'replace',
) -> BackgroundRun[ResultT]:
    """
    Start a call in the background; the canvas hears ``'ai.<name>'`` when it finishes.

    Args:
        call: What to run, such as ``pick.choose_async(context, options)``.
        name: The name of the run, such as ``'move'``: letters, digits and underscores,
            with dots between parts. Its event is ``'ai.'`` and the name.
        if_running: What happens when a run of the same name has not finished:
            ``'replace'`` cancels it, so the latest call wins; ``'ignore'`` keeps it and
            drops this call; ``'queue'`` runs this one after it; ``'overlap'`` runs both.

    Returns:
        The [`BackgroundRun`][xnano.ai.BackgroundRun].

    Raises:
        ValueError: ``name`` is not a name, or ``if_running`` is not one of its words.
        TerminalClosedError: The canvas is closed.

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

        pick = ChoiceModel(ScriptedDecisionModel({'response': 'jump'}))

        with xnano.new(width=20, height=1) as canvas:
            runs = background(canvas)
            hero = canvas.screen.write('hero')

            @canvas.hook(on='key', keys='enter')
            def ask(context: xnano.Context) -> None:
                runs.start(pick.choose_async(context, ['jump', 'duck']), name='move')

            @canvas.hook(on='ai.move')
            def moved(context: xnano.Context) -> None:
                hero.text = f'hero: {runs.result(context).choice}'

            canvas.push(Event.key_press('enter'))
            canvas.clock.step()
            assert canvas.screen.render() == 'hero: jump'
        ```
    """
    canvas = self._canvas
    if not isinstance(name, str) or not _NAME.fullmatch(name):
        _close(call)
        raise ValueError(
            f'A background run is named with letters, digits and underscores, with dots '
            f"between parts, such as name='move' or name='hero.move', but got {name!r}."
        )
    if if_running not in _IF_RUNNING:
        _close(call)
        raise ValueError(
            f'if_running must be one of {", ".join(repr(word) for word in _IF_RUNNING)}, '
            f'but was {if_running!r}.'
        )
    canvas._require_open()
    run: BackgroundRun[ResultT] = BackgroundRun(name, f'{name}#{next(self._counter)}')
    with self._lock:
        self._runs[run._identifier] = run
    root = canvas._canvas
    if not root._host.is_autonomous and (
        root._event_loop is None or root._event_loop.is_closed()
    ):
        # A manual clock and no event loop: run now, and be heard at the next step.
        try:
            run._result = _run_blocking(call, None)
        except Exception as error:
            run.error = error
        run.is_finished = True
        self._deliver(run)
        return run
    self._schedule(run, call, if_running)
    return run

run

run(context: Context[Any, Any]) -> BackgroundRun[Any]

The run whose finishing event a hook heard.

Parameters:

  • context (Context[Any, Any]) –

    The context of a hook on a run's event, such as on='ai.move'.

Raises:

  • TerminalError –

    The context's event is not the finishing event of one of these runs.

Source code in xnano/ai/_background.py
def run(self, context: Context[Any, Any]) -> BackgroundRun[Any]:
    """
    The run whose finishing event a hook heard.

    Args:
        context: The context of a hook on a run's event, such as ``on='ai.move'``.

    Raises:
        TerminalError: The context's event is not the finishing event of one of these runs.
    """
    event = context.event
    identifier = getattr(event, 'custom_data', None)
    with self._lock:
        run = self._runs.get(identifier) if isinstance(identifier, str) else None
    if run is None:
        name = getattr(event, 'custom_name', None)
        raise TerminalError(
            f'This hook heard {name!r}, which is not the event of a background run of this '
            f"canvas. Read results in a hook on the run's event, such as "
            f"on='ai.move' for runs.start(..., name='move')."
        )
    return run

result

result(context: Context[Any, Any]) -> Any

What the run whose event a hook heard returned.

Parameters:

  • context (Context[Any, Any]) –

    The context of a hook on a run's event, such as on='ai.move'.

Raises:

Source code in xnano/ai/_background.py
def result(self, context: Context[Any, Any]) -> Any:
    """
    What the run whose event a hook heard returned.

    Args:
        context: The context of a hook on a run's event, such as ``on='ai.move'``.

    Raises:
        TerminalError: The event is not the finishing event of one of these runs.
        BaseException: The error the run's call raised.
    """
    run = self.run(context)
    with self._lock:
        self._runs.pop(run._identifier, None)
    return run.result

Critique dataclass

Critique(score: int, problems: tuple[str, ...])

What a critic saw in a piece: a score, and each problem it would fix.

Attributes:

  • score (int) –

    From 1 (unreadable) to 10 (nothing to fix).

  • problems (tuple[str, ...]) –

    Each problem, in a sentence; none when there is nothing to fix.

GenerationError

GenerationError(message: str, generation: GenerationReport)

Bases: TerminalError

Raised when no answer of the model could be made into what was asked for.

Attributes:

  • generation (GenerationReport) –

    How the generation went: each problem that was sent back to be fixed.

Create the error with the report of the generation.

Methods:

  • __new__ –

    Pick the class that is also TypeError or ValueError for the code.

  • __reduce__ –

    Pickle through the public class, which picks the one for the code again.

Source code in xnano/ai/_generations.py
def __init__(self, message: str, generation: GenerationReport) -> None:
    """Create the error with the report of the generation."""
    super().__init__(message, code='ai.generation')
    self.generation = generation

default_code class-attribute

default_code: TerminalErrorCode = 'canvas.state'

The code of an error of this class that is raised without one.

report property

report: ErrorReport

The whole report: its title and every problem.

details property

details: tuple[ErrorDetail, ...]

The problems, each an ErrorDetail.

code property

The label of the first problem; see TerminalErrorCode.

__new__

__new__(message: str | ErrorReport, *arguments: object, code: TerminalErrorCode | None = None, **keywords: object) -> Self

Pick the class that is also TypeError or ValueError for the code.

Source code in xnano/errors.py
def __new__(
    cls,
    message: str | _ErrorReport,
    *arguments: object,
    code: TerminalErrorCode | None = None,
    **keywords: object,
) -> Self:
    """Pick the class that is also ``TypeError`` or ``ValueError`` for the code."""
    chosen: type[TerminalError] = cls
    if cls is TerminalError:
        first_code = (
            message.details[0].code if isinstance(message, _ErrorReport) else code
        )
        if first_code in _TYPE_CODES:
            chosen = _TerminalTypeError
        elif first_code in _VALUE_CODES:
            chosen = _TerminalValueError
    return cast('Self', _ReportedError.__new__(chosen))

__reduce__

__reduce__() -> tuple[type[TerminalError], tuple[object, ...]]

Pickle through the public class, which picks the one for the code again.

Source code in xnano/errors.py
def __reduce__(self) -> tuple[type[TerminalError], tuple[object, ...]]:
    """Pickle through the public class, which picks the one for the code again."""
    public = TerminalError if type(self) in _HIDDEN_CLASSES else type(self)
    return (public, self.args)

GenerationReport dataclass

GenerationReport(strategy: str, attempts: int, problems: tuple[str, ...], notes: tuple[str, ...], critiques: tuple[Critique, ...] = (), sketch: tuple[str, ...] = ())

How a generation went: the answers sent back to be fixed, and the repairs made.

last_generation of ArtModel, ComponentModel and MusicModel is one.

Attributes:

  • strategy (str) –

    How the model wrote its answer: 'program' or 'svg' for art, 'program' for a component, or 'melody'.

  • attempts (int) –

    How many answers the model gave.

  • problems (tuple[str, ...]) –

    What was wrong with each answer that was sent back, in order.

  • notes (tuple[str, ...]) –

    The safe repairs that were made instead of a retry, such as a colour written '#f8c'.

  • critiques (tuple[Critique, ...]) –

    What the critic said in each round of critique, in order; the piece kept is the one with the best score.

  • sketch (tuple[str, ...]) –

    For art larger than 12 pixels, the sketch the piece was drawn from: one letter per block of 2 by 2 pixels, '.' for an empty block; empty otherwise.

Observation dataclass

Observation(text: str, x: int, y: int, width: int, height: int, state: JSONValue | None = None, event: dict[str, JSONValue] | None = None, frame: dict[str, JSONValue] | None = None)

The canvas, or a part of it, as a model reads it.

Made by observe, and by every task model from the evidence it is given. to_json() is what a decision model is sent; to_prompt() is what a language model reads, with row numbers and a column ruler so that it can name cells.

Attributes:

  • text (str) –

    The characters of the target's cells, one line per row.

  • x (int) –

    The column of the target, in its parent.

  • y (int) –

    The row of the target, in its parent.

  • width (int) –

    The width of the target in cells (in pixels for art).

  • height (int) –

    The height of the target in cells (in pixels for art).

  • state (JSONValue | None) –

    The canvas's state as JSON, or None for a canvas without state.

  • event (dict[str, JSONValue] | None) –

    What the hook heard: its kind (a HookKind) and the details of the input, or None when nothing was heard.

  • frame (dict[str, JSONValue] | None) –

    The frame index, the elapsed_seconds and the canvas's bpm, or None for art.

Examples:

import xnano
from xnano.ai import observe

with xnano.new(width=8, height=2) as canvas:
    label = canvas.screen.write('ok', x=2, y=1)
    observation = observe(label)
assert (observation.text, observation.x, observation.y) == ('ok', 2, 1)
assert observation.to_json()['width'] == 2

Methods:

  • to_json –

    The observation as JSON-like data, as a decision model is sent it.

  • to_prompt –

    The observation as text for a language model.

to_json

to_json() -> dict[str, JSONValue]

The observation as JSON-like data, as a decision model is sent it.

Source code in xnano/ai/_observe.py
def to_json(self) -> dict[str, JSONValue]:
    """The observation as JSON-like data, as a decision model is sent it."""
    value: dict[str, JSONValue] = {
        'text': self.text,
        'x': self.x,
        'y': self.y,
        'width': self.width,
        'height': self.height,
    }
    for name in ('state', 'event', 'frame'):
        part = getattr(self, name)
        if part is not None:
            value[name] = part
    return value

to_prompt

to_prompt() -> str

The observation as text for a language model.

The cells come with a column ruler above them and a row number before each line, then the position, size, event, frame and state as plain lines.

Source code in xnano/ai/_observe.py
def to_prompt(self) -> str:
    """
    The observation as text for a language model.

    The cells come with a column ruler above them and a row number before each line, then
    the position, size, event, frame and state as plain lines.
    """
    lines = [_ruled(self.text, self.width, self.height)]
    lines.append(
        f'position: x={self.x}, y={self.y}; size: {self.width} by {self.height}'
    )
    if self.event is not None:
        lines.append(f'event: {json.dumps(self.event, sort_keys=True)}')
    if self.frame is not None:
        lines.append(f'frame: {json.dumps(self.frame, sort_keys=True)}')
    if self.state is not None:
        lines.append(f'state: {json.dumps(self.state, sort_keys=True)}')
    return '\n'.join(lines)

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)

Animation dataclass

Animation(frames: tuple[Art, ...], fps: float)

Frames of pixel art shown one after another: what ArtModel.animate makes.

Write it like art, with canvas.screen.write(animation): it shows the frame the canvas's clock is on, and moves to the next one fps times a second.

Attributes:

  • frames (tuple[Art, ...]) –

    The frames, in order.

  • fps (float) –

    How many frames are shown each second.

Examples:

import xnano
from xnano.ai.models.art import Animation

blink = Animation(
    frames=(xnano.pixel_art(['#'], {'#': 'white'}), xnano.pixel_art(['.'], {})),
    fps=2,
)
with xnano.new(width=2, height=1) as canvas:
    canvas.screen.write(blink)
    assert blink.frame_at(0.0) is blink.frames[0]
    assert blink.frame_at(0.5) is blink.frames[1]

Methods:

__post_init__

__post_init__() -> None

Check the frames and the rate.

Source code in xnano/ai/models/art.py
def __post_init__(self) -> None:
    """Check the frames and the rate."""
    if not self.frames:
        raise ValueError('An Animation needs at least one frame.')
    if isinstance(self.fps, bool) or not self.fps > 0:
        raise ValueError(f'fps must be above 0, such as 4, but was {self.fps!r}.')

frame_at

frame_at(seconds: float) -> Art

The frame shown seconds after the animation started.

Source code in xnano/ai/models/art.py
def frame_at(self, seconds: float) -> Art:
    """The frame shown ``seconds`` after the animation started."""
    return self.frames[int(seconds * self.fps) % len(self.frames)]

__xnano_write__

__xnano_write__(context: Context[object, object]) -> Art

The frame the canvas's clock is on.

Source code in xnano/ai/models/art.py
def __xnano_write__(self, context: Context[object, object]) -> Art:
    """The frame the canvas's clock is on."""
    return self.frame_at(context.clock.elapsed_seconds)

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

ArtPatch dataclass

ArtPatch(runs: tuple[PixelRun, ...], new_colors: Mapping[str, PaletteColor] = (lambda: MappingProxyType({}))())

A change to pixel art: the runs of pixels it sets, and any colours it adds.

Attributes:

pixel_count property

pixel_count: int

How many pixels the patch sets.

ArtText dataclass

ArtText(rows: tuple[str, ...], palette: Mapping[str, PaletteColor])

Pixel art as a model writes it: rows of one letter per pixel, and a palette with roles.

It is what ArtModel works with: the model names its colours by role under letters, then draws with those letters, and an edit changes letters. The changes that need no model (flip_horizontal, shift, recolor, scaled, apply) cost nothing. to_art() makes the Art to write on a canvas.

Attributes:

  • rows (tuple[str, ...]) –

    The rows, top to bottom, one letter per pixel; '.' is a transparent pixel.

  • palette (Mapping[str, PaletteColor]) –

    The colour of each letter, and what it is for.

  • width (int) –

    The width in pixels.

  • height (int) –

    The height in pixels.

Examples:

from xnano.ai.models.art import ArtText, PaletteColor

text = ArtText(
    rows=('.oo.', 'obbo', '.oo.'),
    palette={'o': PaletteColor('outline', '#1a1c2c'), 'b': PaletteColor('base', '#b13e53')},
)
assert text.flip_vertical().rows == text.rows
assert text.to_art().width == 4

Methods:

  • __post_init__ –

    Check that the rows are even and use only letters of the palette.

  • to_art –

    Make the Art of these rows and palette.

  • from_art –

    The rows and palette of art: the ones it was made from, or read from its pixels.

  • labelled –

    The rows with a column ruler above them and the row number before each, for a prompt.

  • palette_text –

    The palette as one line per letter, o = outline #1a1c2c, for a prompt.

  • flip_horizontal –

    The art mirrored left to right.

  • flip_vertical –

    The art mirrored top to bottom.

  • shift –

    The art moved by x pixels right and y down, inside the same size.

  • recolor –

    The art with new colours for some letters, keeping their roles.

  • scaled –

    The art with every pixel made factor pixels wide and tall.

  • apply –

    The art with a patch applied: its runs written, its new colours added.

width property

width: int

The width in pixels.

height property

height: int

The height in pixels.

__post_init__

__post_init__() -> None

Check that the rows are even and use only letters of the palette.

Source code in xnano/ai/models/art.py
def __post_init__(self) -> None:
    """Check that the rows are even and use only letters of the palette."""
    rows = tuple(self.rows)
    object.__setattr__(self, 'rows', rows)
    object.__setattr__(self, 'palette', MappingProxyType(dict(self.palette)))
    if not rows or not rows[0]:
        raise ValueError('ArtText needs at least one row of at least one pixel.')
    width = len(rows[0])
    for index, row in enumerate(rows):
        if len(row) != width:
            raise ValueError(
                f'Row {index} of the art has {len(row)} pixels, but row 0 has {width}. '
                f'Give every row the same number of letters.'
            )
        unknown = sorted(set(row) - set(self.palette) - {_TRANSPARENT})
        if unknown:
            raise ValueError(
                f'Row {index} uses {", ".join(map(repr, unknown))}, which the palette '
                f'does not name. Add them to the palette, or use {_TRANSPARENT!r} for a '
                f'transparent pixel.'
            )

to_art

to_art(*, symbol: str | None = None, encoding: PixelEncoding = 'half_blocks', borders: bool = False) -> Art

Make the Art of these rows and palette.

Parameters:

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

    A name to register the art under in symbols.

  • encoding (PixelEncoding, default: 'half_blocks' ) –

    How the pixels are packed into cells, as for pixel_art.

  • borders (bool, default: False ) –

    Whether the art shows its edge in box-drawing characters, as for pixel_art.

Source code in xnano/ai/models/art.py
def to_art(
    self,
    *,
    symbol: str | None = None,
    encoding: PixelEncoding = 'half_blocks',
    borders: bool = False,
) -> Art:
    """
    Make the [`Art`][xnano.art.Art] of these rows and palette.

    Args:
        symbol: A name to register the art under in [`symbols`][xnano.symbols].
        encoding: How the pixels are packed into cells, as for [`pixel_art`][xnano.pixel_art].
        borders: Whether the art shows its edge in box-drawing characters, as for
            [`pixel_art`][xnano.pixel_art].
    """
    art = pixel_art(
        list(self.rows),
        {letter: color.color for letter, color in self.palette.items()},
        symbol=symbol,
        encoding=encoding,
        borders=borders,
    )
    _text_of[art] = self
    return art

from_art classmethod

from_art(art: Art) -> ArtText

The rows and palette of art: the ones it was made from, or read from its pixels.

Art made by ArtModel or to_art gives back the model's own letters and roles. Other art is read pixel by pixel: each colour gets a letter, the darkest the 'outline' role and the others 'detail'.

Raises:

  • ValueError –

    The art is a world, which has no pixels of its own.

Source code in xnano/ai/models/art.py
@classmethod
def from_art(cls, art: Art) -> ArtText:
    """
    The rows and palette of art: the ones it was made from, or read from its pixels.

    Art made by [`ArtModel`][xnano.ai.models.art.ArtModel] or ``to_art`` gives back the model's own
    letters and roles. Other art is read pixel by pixel: each colour gets a letter, the
    darkest the ``'outline'`` role and the others ``'detail'``.

    Raises:
        ValueError: The art is a world, which has no pixels of its own.
    """
    known = _text_of.get(art)
    if known is not None:
        return known
    pixels = art.pixels
    if pixels is None:
        raise ValueError(
            'This art is a world, which has no pixels of its own to read. Give the art '
            'of one of its children, such as world.children[0].'
        )
    colors: dict[tuple[int, int, int], str] = {}
    rows = []
    letters = iter('abcdefghijklmnpqrstuvwxyz')
    for y in range(art.height):
        row = []
        for x in range(art.width):
            start = (y * art.width + x) * 4
            red, green, blue, alpha = pixels[start : start + 4]
            if alpha == 0:
                row.append(_TRANSPARENT)
                continue
            key = (red, green, blue)
            if key not in colors:
                colors[key] = next(letters, '?')
                if colors[key] == '?':
                    raise ValueError(
                        'This art has more than 25 colours, more than a palette of '
                        'letters can name. Reduce its colours before editing it.'
                    )
            row.append(colors[key])
        rows.append(''.join(row))
    darkest = min(colors, key=sum, default=None)
    palette = {
        letter: PaletteColor(
            'outline' if key == darkest else 'detail',
            '#{:02x}{:02x}{:02x}'.format(*key),
        )
        for key, letter in colors.items()
    }
    return cls(rows=tuple(rows), palette=palette)

labelled

labelled() -> str

The rows with a column ruler above them and the row number before each, for a prompt.

Source code in xnano/ai/models/art.py
def labelled(self) -> str:
    """The rows with a column ruler above them and the row number before each, for a prompt."""
    return _ruled('\n'.join(self.rows), self.width, self.height)

palette_text

palette_text() -> str

The palette as one line per letter, o = outline #1a1c2c, for a prompt.

Source code in xnano/ai/models/art.py
def palette_text(self) -> str:
    """The palette as one line per letter, ``o = outline #1a1c2c``, for a prompt."""
    return '\n'.join(
        f'{letter} = {color.role} {color.color}'
        for letter, color in self.palette.items()
    )

flip_horizontal

flip_horizontal() -> ArtText

The art mirrored left to right.

Source code in xnano/ai/models/art.py
def flip_horizontal(self) -> ArtText:
    """The art mirrored left to right."""
    return ArtText(tuple(row[::-1] for row in self.rows), self.palette)

flip_vertical

flip_vertical() -> ArtText

The art mirrored top to bottom.

Source code in xnano/ai/models/art.py
def flip_vertical(self) -> ArtText:
    """The art mirrored top to bottom."""
    return ArtText(self.rows[::-1], self.palette)

shift

shift(x: int = 0, y: int = 0) -> ArtText

The art moved by x pixels right and y down, inside the same size.

Source code in xnano/ai/models/art.py
def shift(self, x: int = 0, y: int = 0) -> ArtText:
    """The art moved by ``x`` pixels right and ``y`` down, inside the same size."""
    width, height = self.width, self.height
    blank = _TRANSPARENT * width
    rows = []
    for row_index in range(height):
        source = row_index - y
        if not 0 <= source < height:
            rows.append(blank)
            continue
        row = self.rows[source]
        moved = (
            (_TRANSPARENT * x + row)[:width]
            if x >= 0
            else (row[-x:] + _TRANSPARENT * -x)
        )
        rows.append(moved)
    return ArtText(tuple(rows), self.palette)

recolor

recolor(colors: Mapping[str, str]) -> ArtText

The art with new colours for some letters, keeping their roles.

Parameters:

  • colors (Mapping[str, str]) –

    The new '#rrggbb' colour of each letter to change.

Raises:

Source code in xnano/ai/models/art.py
def recolor(self, colors: Mapping[str, str]) -> ArtText:
    """
    The art with new colours for some letters, keeping their roles.

    Args:
        colors: The new ``'#rrggbb'`` colour of each letter to change.

    Raises:
        ValueError: A letter is not in the palette.
    """
    palette = dict(self.palette)
    for letter, color in colors.items():
        if letter not in palette:
            raise ValueError(
                f'recolor() was given {letter!r}, which the palette does not have. Its '
                f'letters are {", ".join(map(repr, palette))}.'
            )
        palette[letter] = PaletteColor(
            palette[letter].role, _normalized_color(color)[0]
        )
    return ArtText(self.rows, palette)

scaled

scaled(factor: int) -> ArtText

The art with every pixel made factor pixels wide and tall.

Raises:

  • ValueError –

    factor is not a whole number of 1 or more.

Source code in xnano/ai/models/art.py
def scaled(self, factor: int) -> ArtText:
    """
    The art with every pixel made ``factor`` pixels wide and tall.

    Raises:
        ValueError: ``factor`` is not a whole number of 1 or more.
    """
    if isinstance(factor, bool) or not isinstance(factor, int) or factor < 1:
        raise ValueError(
            f'scaled() needs a whole number of 1 or more, such as 2, but got {factor!r}.'
        )
    rows = tuple(
        ''.join(letter * factor for letter in row)
        for row in self.rows
        for _ in range(factor)
    )
    return ArtText(rows, self.palette)

apply

apply(patch: ArtPatch) -> ArtText

The art with a patch applied: its runs written, its new colours added.

Raises:

  • ValueError –

    A run is outside the art, or uses a letter neither palette names.

Source code in xnano/ai/models/art.py
def apply(self, patch: ArtPatch) -> ArtText:
    """
    The art with a patch applied: its runs written, its new colours added.

    Raises:
        ValueError: A run is outside the art, or uses a letter neither palette names.
    """
    palette = {**self.palette, **patch.new_colors}
    grid = [list(row) for row in self.rows]
    for run in patch.runs:
        if (
            not 0 <= run.row < self.height
            or run.column < 0
            or (run.column + len(run.letters) > self.width)
        ):
            raise ValueError(
                f'The run at row {run.row}, column {run.column} with '
                f'{len(run.letters)} letters is outside the art, which is {self.width} '
                f'by {self.height} pixels.'
            )
        for offset, letter in enumerate(run.letters):
            grid[run.row][run.column + offset] = letter
    return ArtText(tuple(''.join(row) for row in grid), palette)

PaletteColor dataclass

PaletteColor(role: ColorRole, color: str)

One colour of a palette, and what it is for.

Attributes:

  • role (ColorRole) –

    What the colour is for, such as 'outline' or 'shadow'.

  • color (str) –

    The colour as '#rrggbb'.

PixelRun dataclass

PixelRun(row: int, column: int, letters: str)

Pixels set in a row, from a column to the right: one letter of the palette per pixel.

Attributes:

  • row (int) –

    The row, from 0 at the top.

  • column (int) –

    The first column, from 0 at the left.

  • letters (str) –

    The letters to write, one per pixel; '.' makes a pixel transparent.

Component dataclass

Component(request: str, code: str, width: int, height: int, text: str, _cells: Region[int])

A widget a model wrote: a small program that draws on a canvas of its own size.

Write it like other content, with canvas.screen.write(component): it takes its width and height, and a border or a title given to the write goes around it. Its code runs in the sandbox of xnano.sandbox, so it can only draw.

Attributes:

  • request (str) –

    What was asked for.

  • code (str) –

    The program, in Python.

  • width (int) –

    The width it draws at, in cells.

  • height (int) –

    The height it draws at, in rows.

  • text (str) –

    What it draws, as text.

Examples:

import xnano
from xnano.ai.models.components import ComponentModel
from xnano.ai.testing import scripted_model

answer = {'layout': 'One bold line.', 'program': "canvas.screen.write('Ready', bold=True)"}
components = ComponentModel(scripted_model(answer).model)
badge = components.generate('a ready badge', width=8, height=1)
assert badge.text == 'Ready'
with xnano.new(width=12, height=3) as canvas:
    canvas.screen.write(badge, border='rounded')
    assert canvas.screen.render().splitlines()[1] == '│Ready   │'

Methods:

__xnano_write__

__xnano_write__(context: Context[object, object]) -> Region[int]

The cells the program drew.

Source code in xnano/ai/models/components.py
def __xnano_write__(self, context: Context[object, object]) -> Region[int]:
    """The cells the program drew."""
    return self._cells

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
    )

Decision dataclass

Decision(choice: str, value: object, probabilities: dict[str, float] | None = None, confidence: float | None = None)

The option a ChoiceModel picked, and how sure it was.

Attributes:

  • choice (str) –

    The label that was picked, such as 'left', or 'no_change'.

  • value (object) –

    What the label stands for: the Choice value, what a callable value returned, or the label itself.

  • probabilities (dict[str, float] | None) –

    The probability of every option on a decision model, in the order the options were offered, or None on a language model.

  • confidence (float | None) –

    The backend's own confidence in the pick, or None. It is not how often the pick is right; threshold on margin instead.

Examples:

import random

from xnano.ai.models.decisions import Decision

decision = Decision(
    choice='left', value='left', probabilities={'left': 0.7, 'right': 0.3}
)
assert round(decision.margin, 2) == 0.4
assert decision.sample(random.Random(3)) in ('left', 'right')

Methods:

  • sample –

    Draw an option from the distribution instead of always taking the likeliest.

margin property

margin: float | None

How far the pick is ahead: its probability minus the next one's, or None.

A margin near 0 means two options were nearly tied. Below the margin an action is worth taking for, keep things as they are.

sample

sample(source: Random | None = None, *, temperature: float = 1.0, floor: float = 0.0) -> str

Draw an option from the distribution instead of always taking the likeliest.

Use it for variety that still follows what the model thought likely: a character that mostly, but not always, does the expected thing.

Parameters:

  • source (Random | None, default: None ) –

    Where the random numbers come from, such as random.Random(7) for the same draws on every run; Python's shared generator when None.

  • temperature (float, default: 1.0 ) –

    Above 1 the options are drawn more evenly, below 1 the likeliest is drawn more often; it must be above 0.

  • floor (float, default: 0.0 ) –

    Options less likely than this are never drawn.

Returns:

  • str –

    The label drawn, or choice on a language model, which gives no distribution.

Raises:

Source code in xnano/ai/models/decisions.py
def sample(
    self,
    source: random.Random | None = None,
    *,
    temperature: float = 1.0,
    floor: float = 0.0,
) -> str:
    """
    Draw an option from the distribution instead of always taking the likeliest.

    Use it for variety that still follows what the model thought likely: a character that
    mostly, but not always, does the expected thing.

    Args:
        source: Where the random numbers come from, such as ``random.Random(7)`` for the
            same draws on every run; Python's shared generator when ``None``.
        temperature: Above ``1`` the options are drawn more evenly, below ``1`` the
            likeliest is drawn more often; it must be above ``0``.
        floor: Options less likely than this are never drawn.

    Returns:
        The label drawn, or ``choice`` on a language model, which gives no distribution.

    Raises:
        ValueError: ``temperature`` is not above ``0``.
    """
    if not temperature > 0:
        raise ValueError(
            f'temperature must be above 0, but was {temperature!r}. Use 1.0 to draw as '
            f'the model gave the odds, more to draw more evenly, less to favour the '
            f'likeliest option.'
        )
    probabilities = self.probabilities
    if not probabilities:
        return self.choice
    kept = {
        label: probability ** (1.0 / temperature)
        for label, probability in probabilities.items()
        if probability >= floor and probability > 0
    }
    if not kept:
        return self.choice
    draw = (source or random).random() * sum(kept.values())
    for label, weight in kept.items():
        draw -= weight
        if draw <= 0:
            return label
    return next(reversed(kept))

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

Score dataclass

Score(level: int, label: str, probabilities: dict[str, float] | None = None, expected: float | None = None)

The level of a rubric a JudgeModel placed the evidence at.

Attributes:

  • level (int) –

    The position of the level in the rubric, from 0.

  • label (str) –

    The level as it was written in the rubric.

  • probabilities (dict[str, float] | None) –

    The probability of each level, by its label, on a decision model, or None on a language model.

  • expected (float | None) –

    The probability-weighted mean level on a decision model, between two levels when the model hesitated, or None.

Verdict dataclass

Verdict(question: str, answer: bool, probability: float | None = None, threshold: float = 0.5)

The answer of a JudgeModel to a yes/no question.

Attributes:

  • question (str) –

    The question that was asked.

  • answer (bool) –

    Whether the answer is yes: on a decision model, whether probability is at least threshold.

  • probability (float | None) –

    How likely a yes is on a decision model, or None on a language model.

  • threshold (float) –

    The probability a yes needed.

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

StateTransition dataclass

StateTransition(before: StateT, after: StateT, changes: dict[str, tuple[object, object]], confidence: dict[str, float] | None = None, reason: str | None = None)

Bases: Generic[StateT]

How a StateModel changed a state.

Attributes:

  • before (StateT) –

    The state as it was.

  • after (StateT) –

    The state as it is now; before itself when nothing changed.

  • changes (dict[str, tuple[object, object]]) –

    Each field that changed, with its old and its new value.

  • confidence (dict[str, float] | None) –

    How likely the new value of each field is, on a decision model, or None on a language model.

  • reason (str | None) –

    Why the state changed, as a language model wrote it, or None.

is_changed property

is_changed: bool

Whether any field changed.

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

background

background(canvas: Canvas[Any, Any]) -> BackgroundRuns

The background runs of a canvas, to start slow calls from a plain hook.

A hook must not wait for a model, or the canvas stops drawing until it answers. A hook starts the call in the background instead, and a hook on the run's event uses the answer when it lands. In an async program, an async def hook that awaits the call is the shorter way; background() is for programs that do not await, and for delivering the answer to another hook.

Parameters:

  • canvas (Canvas[Any, Any]) –

    The canvas whose runs to start; a canvas written into another one shares the runs of the outer one.

Returns:

Source code in xnano/ai/_background.py
def background(canvas: Canvas[Any, Any]) -> BackgroundRuns:
    """
    The background runs of a canvas, to start slow calls from a plain hook.

    A hook must not wait for a model, or the canvas stops drawing until it answers. A hook
    starts the call in the background instead, and a hook on the run's event uses the answer
    when it lands. In an async program, an ``async def`` hook that awaits the call is the
    shorter way; ``background()`` is for programs that do not await, and for delivering the
    answer to another hook.

    Args:
        canvas: The canvas whose runs to start; a canvas written into another one shares the
            runs of the outer one.

    Returns:
        The canvas's [`BackgroundRuns`][xnano.ai.BackgroundRuns]; the same each time.
    """
    root = cast('Canvas[object, object]', canvas)._canvas
    runs = root.__dict__.get('_background_runs')
    if runs is None:
        with root._lock:
            runs = root.__dict__.get('_background_runs')
            if runs is None:
                runs = BackgroundRuns(root)
                root._background_runs = runs  # type: ignore[attr-defined]
    return runs

observe

observe(target: object) -> Observation

Read a canvas, a placement, a hook's context, a frame or a piece of art as a model would.

Every task model reads its evidence this way; call it yourself to look at what a model is shown, to log it, or to combine several readings in one piece of evidence.

The cells are what the target draws now. A Context is read as the placement or canvas its hook is on, with the event it heard and the frame it ran in. A Frame from canvas.iter() is the whole canvas at that frame. Art is its pixels, one letter per colour, with the colour each letter stands for after the rows.

Parameters:

  • target (object) –

    A Canvas, Placement, Context, Frame or Art.

Raises:

  • TerminalError –

    target is the context of a writable or playable component, which runs again on every frame it reads, so a model would be asked on every frame. Read the evidence in a hook instead, and keep the answer in state.

  • TypeError –

    target is none of these.

Examples:

import xnano
from xnano.ai import observe

with xnano.new(width=6, height=1) as canvas:
    canvas.screen.write('hello')
    observation = observe(canvas)
assert observation.text == 'hello'
assert observation.frame == {'index': 0, 'elapsed_seconds': 0.0, 'bpm': 120.0}
Source code in xnano/ai/_observe.py
def observe(target: object) -> Observation:
    """
    Read a canvas, a placement, a hook's context, a frame or a piece of art as a model would.

    Every task model reads its evidence this way; call it yourself to look at what a model is
    shown, to log it, or to combine several readings in one piece of evidence.

    The cells are what the target draws now. A [`Context`][xnano.hooks.Context] is read as
    the placement or canvas its hook is on, with the event it heard and the frame it ran in. A
    [`Frame`][xnano.hooks.Frame] from ``canvas.iter()`` is the whole canvas at that frame.
    [`Art`][xnano.art.Art] is its pixels, one letter per colour, with the colour each letter
    stands for after the rows.

    Args:
        target: A ``Canvas``, ``Placement``, ``Context``, ``Frame`` or ``Art``.

    Raises:
        TerminalError: ``target`` is the context of a ``writable`` or ``playable``
            component, which runs again on every frame it reads, so a model would be asked on
            every frame. Read the evidence in a hook instead, and keep the answer in state.
        TypeError: ``target`` is none of these.

    Examples:
        ```python
        import xnano
        from xnano.ai import observe

        with xnano.new(width=6, height=1) as canvas:
            canvas.screen.write('hello')
            observation = observe(canvas)
        assert observation.text == 'hello'
        assert observation.frame == {'index': 0, 'elapsed_seconds': 0.0, 'bpm': 120.0}
        ```
    """
    if isinstance(target, Observation):
        return target
    if isinstance(target, Context):
        return _observe_context(cast('Context[object, object]', target))
    if isinstance(target, Frame):
        return _observe_canvas(cast('Canvas[object, object]', target.canvas), event=None)
    if isinstance(target, Placement):
        return _observe_placement(cast('Placement[object, object]', target), event=None)
    if isinstance(target, Canvas):
        return _observe_canvas(cast('Canvas[object, object]', target), event=None)
    if isinstance(target, Art):
        return _observe_art(target)
    raise TypeError(
        f'observe() reads a Canvas, a Placement, a hook Context, a Frame or an Art, but got '
        f'{target!r} of type {type(target).__name__}. To give a model other facts, put them '
        f'beside the canvas in a dictionary, such as {{"screen": canvas, "score": 3}}.'
    )

decide

decide(model: ChoiceModel, options: Options, *, question: str | None = None, on: HookTrigger[Any, Any] | None = None, keys: KeyName | tuple[KeyName, ...] | None = None, every: float | None = None, after: float | None = None, threshold: float = 0.0, no_change: str | None = 'nothing needs to change now', if_running: IfRunning = 'replace') -> ContextualOperation[Any, Any]

Let a choice model decide what a placement does, when something happens to it.

Attach the result with placement | decide(...). When the hook's event comes (on, keys, every and after are the ones hook() takes), the model is asked in the background with the hook's context as evidence, so the canvas goes on drawing. When the answer lands, a pick whose margin is below threshold counts as no_change; then the decision is kept in the target's state under 'decision' (its choice, margin and probabilities), a callable value of the option picked is called, and a value that is an operation, a style or an effect is applied to the target, as a hook's return value is.

Parameters:

  • model (ChoiceModel) –

    The ChoiceModel that decides.

  • options (Options) –

    The options; see Options.

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

    What is being decided, such as 'How should the hero react?'.

  • on (HookTrigger[Any, Any] | None, default: None ) –

    When to decide, as hook() takes it, such as on='key'.

  • keys (KeyName | tuple[KeyName, ...] | None, default: None ) –

    The keys that decide, such as keys='enter'.

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

    Decide every this many seconds.

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

    Decide once after this many seconds.

  • threshold (float, default: 0.0 ) –

    How far the pick must lead the next option, from 0 to 1; below it the decision is no_change. Set it by what a wrong action costs.

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

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

  • if_running (IfRunning, default: 'replace' ) –

    What a new decision does to one that has not landed; 'replace', so the latest input wins. See IfRunning.

Returns:

Raises:

  • ValueError –

    on was not given, an option or threshold is not valid, or if_running is not one of its words.

Examples:

import xnano
from pydantic_ai import Choice
from xnano.ai.models.decisions import ChoiceModel
from xnano.ai import decide
from xnano.ai.testing import ScriptedDecisionModel
from xnano.events import Event
from xnano_core import Style

pick = ChoiceModel(ScriptedDecisionModel({'response': {'warn': 0.9, 'rest': 0.1}}))

with xnano.new(width=20, height=1) as canvas:
    hero = canvas.screen.write('hero')
    hero | decide(
        pick,
        {'warn': Choice('the hero is in danger', value=Style('red')), 'rest': 'rest'},
        on='key',
        keys='enter',
        threshold=0.5,
    )
    canvas.push(Event.key_press('enter'))
    canvas.clock.step()
    canvas.clock.step()
    assert hero.state.get('decision')['choice'] == 'warn'
Source code in xnano/ai/_plugins.py
def decide(
    model: ChoiceModel,
    options: Options,
    *,
    question: str | None = None,
    on: HookTrigger[Any, Any] | None = None,
    keys: KeyName | tuple[KeyName, ...] | None = None,
    every: float | None = None,
    after: float | None = None,
    threshold: float = 0.0,
    no_change: str | None = 'nothing needs to change now',
    if_running: IfRunning = 'replace',
) -> ContextualOperation[Any, Any]:
    """
    Let a choice model decide what a placement does, when something happens to it.

    Attach the result with ``placement | decide(...)``. When the hook's event comes (``on``,
    ``keys``, ``every`` and ``after`` are the ones ``hook()`` takes), the model is asked in the
    background with the hook's context as evidence, so the canvas goes on drawing. When the
    answer lands, a pick whose margin is below ``threshold`` counts as ``no_change``; then the
    decision is kept in the target's state under ``'decision'`` (its ``choice``, ``margin``
    and ``probabilities``), a callable value of the option picked is called, and a value that
    is an operation, a style or an effect is applied to the target, as a hook's return value is.

    Args:
        model: The [`ChoiceModel`][xnano.ai.models.decisions.ChoiceModel] that decides.
        options: The options; see [`Options`][xnano.ai.models.decisions.Options].
        question: What is being decided, such as ``'How should the hero react?'``.
        on: When to decide, as ``hook()`` takes it, such as ``on='key'``.
        keys: The keys that decide, such as ``keys='enter'``.
        every: Decide every this many seconds.
        after: Decide once after this many seconds.
        threshold: How far the pick must lead the next option, from 0 to 1; below it the
            decision is ``no_change``. Set it by what a wrong action costs.
        no_change: What the ``no_change`` option means, or ``None`` to offer only yours.
        if_running: What a new decision does to one that has not landed; ``'replace'``, so
            the latest input wins. See [`IfRunning`][xnano.hooks.IfRunning].

    Returns:
        The plugin: ``placement | plugin`` attaches it, and ``plugin.remove()`` detaches it.

    Raises:
        ValueError: ``on`` was not given, an option or ``threshold`` is not valid, or
            ``if_running`` is not one of its words.

    Examples:
        ```python
        import xnano
        from pydantic_ai import Choice
        from xnano.ai.models.decisions import ChoiceModel
        from xnano.ai import decide
        from xnano.ai.testing import ScriptedDecisionModel
        from xnano.events import Event
        from xnano_core import Style

        pick = ChoiceModel(ScriptedDecisionModel({'response': {'warn': 0.9, 'rest': 0.1}}))

        with xnano.new(width=20, height=1) as canvas:
            hero = canvas.screen.write('hero')
            hero | decide(
                pick,
                {'warn': Choice('the hero is in danger', value=Style('red')), 'rest': 'rest'},
                on='key',
                keys='enter',
                threshold=0.5,
            )
            canvas.push(Event.key_press('enter'))
            canvas.clock.step()
            canvas.clock.step()
            assert hero.state.get('decision')['choice'] == 'warn'
        ```
    """
    offered = _offered(options, no_change)
    _check_threshold(threshold)
    _check_if_running(if_running)
    _check_when('decide', on)
    meanings = {label: meaning or label for label, (meaning, _) in offered.items()}
    plain = {label: meaning for label, meaning in meanings.items() if label != NO_CHANGE}

    def start(context: Context[Any, Any]) -> object:
        return model.choose_async(context, plain, question=question, no_change=no_change)

    def receive(context: Context[Any, Any], answer: object) -> object:
        decision = cast('Decision', answer)
        margin = decision.margin
        if decision.choice != NO_CHANGE and margin is not None and margin < threshold:
            decision = Decision(
                choice=NO_CHANGE,
                value=NO_CHANGE,
                probabilities=decision.probabilities,
                confidence=decision.confidence,
            )
        kept: dict[str, JSONValue] = {
            'choice': decision.choice,
            'margin': decision.margin,
            'probabilities': cast('JSONValue', decision.probabilities),
        }
        context.target.state.set('decision', kept)
        if decision.choice == NO_CHANGE:
            return None
        value = _resolve_blocking(offered[decision.choice][1], decision.choice, 'decide')
        return _applicable(value)

    return _ModelPlugin(
        kind='decide',
        start=start,
        receive=receive,
        on=on,
        every=every,
        after=after,
        keys=keys,
        if_running=if_running,
    )

watch

watch(model: JudgeModel, question: str, *, on: HookTrigger[Any, Any] | None = None, keys: KeyName | tuple[KeyName, ...] | None = None, every: float | None = None, after: float | None = None, threshold: float = 0.5, yes: Operation | Style | Callable[[], object] | None = None, no: Operation | Style | Callable[[], object] | None = None, if_running: IfRunning = 'replace') -> ContextualOperation[Any, Any]

Let a judge model keep answering a yes/no question about a placement.

Attach the result with placement | watch(...). When the hook's event comes, the model is asked in the background with the hook's context as evidence; when the answer lands, the verdict is kept in the target's state under 'verdict' (its answer and probability), so a writable that reads it runs again, and yes or no is applied to the target when it is an operation, a style or an effect, or called when it is a function.

Parameters:

  • model (JudgeModel) –

    The JudgeModel that answers.

  • question (str) –

    The question, such as 'Is the server under strain?'.

  • on (HookTrigger[Any, Any] | None, default: None ) –

    When to ask, as hook() takes it.

  • keys (KeyName | tuple[KeyName, ...] | None, default: None ) –

    The keys that ask, such as keys='enter'.

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

    Ask every this many seconds.

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

    Ask once after this many seconds.

  • threshold (float, default: 0.5 ) –

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

  • yes (Operation | Style | Callable[[], object] | None, default: None ) –

    What to apply or call when the answer is yes.

  • no (Operation | Style | Callable[[], object] | None, default: None ) –

    What to apply or call when the answer is no.

  • if_running (IfRunning, default: 'replace' ) –

    What a new question does to one that has not been answered.

Returns:

Raises:

  • ValueError –

    on was not given, threshold is not from 0 to 1, or if_running is not one of its words.

Examples:

import xnano
from xnano.ai.models.decisions import JudgeModel
from xnano.ai import watch
from xnano.ai.testing import ScriptedDecisionModel
from xnano_core import Style

judge = JudgeModel(ScriptedDecisionModel({'answer': 0.8}))

with xnano.new(width=20, height=1) as canvas:
    gauge = canvas.screen.write('CPU 97%')
    gauge | watch(
        judge, 'Is the server under strain?', on='tick', every=1.0, yes=Style('red')
    )
    canvas.clock.step(delta_seconds=1.0)
    canvas.clock.step()
    assert gauge.state.get('verdict')['answer'] is True
Source code in xnano/ai/_plugins.py
def watch(
    model: JudgeModel,
    question: str,
    *,
    on: HookTrigger[Any, Any] | None = None,
    keys: KeyName | tuple[KeyName, ...] | None = None,
    every: float | None = None,
    after: float | None = None,
    threshold: float = 0.5,
    yes: _core.Operation | _core.Style | Callable[[], object] | None = None,
    no: _core.Operation | _core.Style | Callable[[], object] | None = None,
    if_running: IfRunning = 'replace',
) -> ContextualOperation[Any, Any]:
    """
    Let a judge model keep answering a yes/no question about a placement.

    Attach the result with ``placement | watch(...)``. When the hook's event comes, the model
    is asked in the background with the hook's context as evidence; when the answer lands, the
    verdict is kept in the target's state under ``'verdict'`` (its ``answer`` and
    ``probability``), so a ``writable`` that reads it runs again, and ``yes`` or ``no`` is
    applied to the target when it is an operation, a style or an effect, or called when it is a
    function.

    Args:
        model: The [`JudgeModel`][xnano.ai.models.decisions.JudgeModel] that answers.
        question: The question, such as ``'Is the server under strain?'``.
        on: When to ask, as ``hook()`` takes it.
        keys: The keys that ask, such as ``keys='enter'``.
        every: Ask every this many seconds.
        after: Ask once after this many seconds.
        threshold: How likely a yes has to be, on a decision model.
        yes: What to apply or call when the answer is yes.
        no: What to apply or call when the answer is no.
        if_running: What a new question does to one that has not been answered.

    Returns:
        The plugin: ``placement | plugin`` attaches it, and ``plugin.remove()`` detaches it.

    Raises:
        ValueError: ``on`` was not given, ``threshold`` is not from 0 to 1, or ``if_running``
            is not one of its words.

    Examples:
        ```python
        import xnano
        from xnano.ai.models.decisions import JudgeModel
        from xnano.ai import watch
        from xnano.ai.testing import ScriptedDecisionModel
        from xnano_core import Style

        judge = JudgeModel(ScriptedDecisionModel({'answer': 0.8}))

        with xnano.new(width=20, height=1) as canvas:
            gauge = canvas.screen.write('CPU 97%')
            gauge | watch(
                judge, 'Is the server under strain?', on='tick', every=1.0, yes=Style('red')
            )
            canvas.clock.step(delta_seconds=1.0)
            canvas.clock.step()
            assert gauge.state.get('verdict')['answer'] is True
        ```
    """
    _check_threshold(threshold)
    _check_if_running(if_running)
    _check_when('watch', on)

    def start(context: Context[Any, Any]) -> object:
        return model.ask_async(context, question, threshold=threshold)

    def receive(context: Context[Any, Any], answer: object) -> object:
        verdict = cast('Verdict', answer)
        kept: dict[str, JSONValue] = {
            'question': verdict.question,
            'answer': verdict.answer,
            'probability': verdict.probability,
        }
        context.target.state.set('verdict', kept)
        value = yes if verdict.answer else no
        if value is None:
            return None
        return _applicable(
            _resolve_blocking(value, '', 'watch') if callable(value) else value
        )

    return _ModelPlugin(
        kind='watch',
        start=start,
        receive=receive,
        on=on,
        every=every,
        after=after,
        keys=keys,
        if_running=if_running,
    )

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)

stream_into

stream_into(placement: Placement[Any, Any], pieces: Iterable[str], *, debounce_seconds: float = 1 / 30) -> str

Show text in a placement as its pieces arrive, for code that does not await.

The same as stream_into_async, with pieces such as TextModel.stream(...).

Examples:

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

writer = TextModel(scripted_model('Thunder rolls.').model)
with xnano.new(width=20, height=1) as canvas:
    label = canvas.screen.write('')
    assert stream_into(label, writer.stream('Narrate.')) == 'Thunder rolls.'
    assert canvas.screen.render() == 'Thunder rolls.'
Source code in xnano/ai/models/text.py
def stream_into(
    placement: Placement[Any, Any],
    pieces: Iterable[str],
    *,
    debounce_seconds: float = 1 / 30,
) -> str:
    """
    Show text in a placement as its pieces arrive, for code that does not await.

    The same as [`stream_into_async`][xnano.ai.models.text.stream_into_async], with pieces such as
    ``TextModel.stream(...)``.

    Examples:
        ```python
        import xnano
        from xnano.ai.models.text import TextModel, stream_into
        from xnano.ai.testing import scripted_model

        writer = TextModel(scripted_model('Thunder rolls.').model)
        with xnano.new(width=20, height=1) as canvas:
            label = canvas.screen.write('')
            assert stream_into(label, writer.stream('Narrate.')) == 'Thunder rolls.'
            assert canvas.screen.render() == 'Thunder rolls.'
        ```
    """
    _check_debounce(debounce_seconds)
    text: list[str] = []
    shown = ''
    last = 0.0
    try:
        for piece in pieces:
            text.append(piece)
            now = time.monotonic()
            if now - last >= debounce_seconds:
                shown = ''.join(text)
                placement.text = shown
                last = now
    finally:
        whole = ''.join(text)
        if whole != shown and not placement._removed:
            placement.text = whole
    return whole

stream_into_async async

stream_into_async(placement: Placement[Any, Any], pieces: AsyncIterable[str], *, debounce_seconds: float = 1 / 30) -> str

Show text in a placement as its pieces arrive, and return the whole text.

The placement's text is replaced at most every debounce_seconds with everything that arrived so far, so a fast stream costs a few redraws, not one per piece. When the stream ends or is cancelled, the placement keeps all the text that arrived.

Parameters:

  • placement (Placement[Any, Any]) –

    Where to show the text; it grows with it, unless it was given a size.

  • pieces (AsyncIterable[str]) –

    The pieces, such as TextModel.stream_async(...).

  • debounce_seconds (float, default: 1 / 30 ) –

    The least time between two redraws.

Returns:

  • str –

    The whole text.

Examples:

import asyncio

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

writer = TextModel(scripted_model('The rain stops.').model)


async def main() -> str:
    async with xnano.new(width=20, height=1) as canvas:
        label = canvas.screen.write('')
        await stream_into_async(label, writer.stream_async('Narrate.'))
        return canvas.screen.render()


assert asyncio.run(main()) == 'The rain stops.'
Source code in xnano/ai/models/text.py
async def stream_into_async(
    placement: Placement[Any, Any],
    pieces: AsyncIterable[str],
    *,
    debounce_seconds: float = 1 / 30,
) -> str:
    """
    Show text in a placement as its pieces arrive, and return the whole text.

    The placement's text is replaced at most every ``debounce_seconds`` with everything that
    arrived so far, so a fast stream costs a few redraws, not one per piece. When the stream ends
    or is cancelled, the placement keeps all the text that arrived.

    Args:
        placement: Where to show the text; it grows with it, unless it was given a size.
        pieces: The pieces, such as ``TextModel.stream_async(...)``.
        debounce_seconds: The least time between two redraws.

    Returns:
        The whole text.

    Examples:
        ```python
        import asyncio

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

        writer = TextModel(scripted_model('The rain stops.').model)


        async def main() -> str:
            async with xnano.new(width=20, height=1) as canvas:
                label = canvas.screen.write('')
                await stream_into_async(label, writer.stream_async('Narrate.'))
                return canvas.screen.render()


        assert asyncio.run(main()) == 'The rain stops.'
        ```
    """
    _check_debounce(debounce_seconds)
    text: list[str] = []
    shown = ''
    last = 0.0
    try:
        async for piece in pieces:
            text.append(piece)
            now = time.monotonic()
            if now - last >= debounce_seconds:
                shown = ''.join(text)
                placement.text = shown
                last = now
    finally:
        whole = ''.join(text)
        if whole != shown and not placement._removed:
            placement.text = whole
    return whole