Skip to content

form

Class info

Re-exported classes

Class Module Description
AnyNode promptantic.form.nodes Anything (an empty schema): entered as JSON.
ArrayNode promptantic.form.nodes A list of items of one kind.
BooleanNode promptantic.form.nodes True or false.
Choice promptantic.form.nodes One allowed value of a :class:ChoiceNode.
ChoiceNode promptantic.form.nodes One of a fixed set of values (enum, const, or oneOf of titled consts).
FieldError promptantic.form.values Input that can't become a value of the field (e.g. "abc" for a number).
FormCancelledError promptantic.form.target The user closed the form without submitting it.
FormTarget promptantic.form.target The schema a form is built from, and how its result is validated.
FormValidationError promptantic.form.target The finished value doesn't validate.
Issue promptantic.form.target One problem with a finished value, at a path into it ((): the whole value).
Meta promptantic.form.nodes What every node carries besides its kind: labels, default, flags.
NullNode promptantic.form.nodes Only null (e.g. the None member of a union that isn't just "optional").
NumberNode promptantic.form.nodes A number; integer for whole numbers.
ObjectNode promptantic.form.nodes Named fields, plus optionally free keys (additionalProperties with a schema).
Property promptantic.form.nodes One field of an :class:ObjectNode.
StringNode promptantic.form.nodes Free text, optionally constrained.
TupleNode promptantic.form.nodes A fixed sequence of positions, each of its own kind (prefixItems).
UnionNode promptantic.form.nodes One of several alternatives (anyOf / oneOf / several types).
Variant promptantic.form.nodes One alternative of a :class:UnionNode.

🛈 DocStrings

The UI-independent core: JSON Schema -> form tree -> values -> validation.

Renderers (Textual, prompt-toolkit) build their widgets from the tree of :func:build_form, check fields with :func:field_errors while the user types, and hand the finished value to :meth:FormTarget.validate.

UNSET module-attribute

UNSET: Final = _Unset.UNSET

No value given (distinct from None, which is JSON null).

FormNode

A node of the form tree.

AnyNode dataclass

Bases: NodeBase

Anything (an empty schema): entered as JSON.

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True)
class AnyNode(NodeBase):
    """Anything (an empty schema): entered as JSON."""

    kind: Literal["any"] = "any"

ArrayNode dataclass

Bases: NodeBase

A list of items of one kind.

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True, eq=False)
class ArrayNode(NodeBase):
    """A list of items of one kind."""

    kind: Literal["array"] = "array"
    min_items: int | None = None
    max_items: int | None = None
    unique: bool = False
    build_items: Callable[[], FormNode] | None = field(default=None, repr=False)

    @cached_property
    def items(self) -> FormNode:
        """The node every item follows (built on first access)."""
        if self.build_items is None:
            return AnyNode(meta=Meta())
        return self.build_items()

    @property
    def multi_choice(self) -> bool:
        """Items are choices and unique: a pick-several list rather than an item editor."""
        return isinstance(self.items, ChoiceNode) and not self.items.fixed

items cached property

items: FormNode

The node every item follows (built on first access).

multi_choice property

multi_choice: bool

Items are choices and unique: a pick-several list rather than an item editor.

BooleanNode dataclass

Bases: NodeBase

True or false.

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True)
class BooleanNode(NodeBase):
    """True or false."""

    kind: Literal["boolean"] = "boolean"

Choice dataclass

One allowed value of a :class:ChoiceNode.

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True)
class Choice:
    """One allowed value of a :class:`ChoiceNode`."""

    value: Any
    label: str

ChoiceNode dataclass

Bases: NodeBase

One of a fixed set of values (enum, const, or oneOf of titled consts).

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True)
class ChoiceNode(NodeBase):
    """One of a fixed set of values (``enum``, ``const``, or ``oneOf`` of titled consts)."""

    kind: Literal["choice"] = "choice"
    choices: tuple[Choice, ...] = ()

    @property
    def fixed(self) -> bool:
        """Only one value is possible (``const``): nothing to ask."""
        return len(self.choices) == 1 and not self.nullable

fixed property

fixed: bool

Only one value is possible (const): nothing to ask.

FieldError

Bases: ValueError

Input that can't become a value of the field (e.g. "abc" for a number).

Source code in src/promptantic/form/values.py
class FieldError(ValueError):
    """Input that can't become a value of the field (e.g. "abc" for a number)."""

FormCancelledError

Bases: Exception

The user closed the form without submitting it.

Source code in src/promptantic/form/target.py
class FormCancelledError(Exception):
    """The user closed the form without submitting it."""

FormTarget dataclass

The schema a form is built from, and how its result is validated.

Source code in src/promptantic/form/target.py
@dataclass(frozen=True)
class FormTarget[T]:
    """The schema a form is built from, and how its result is validated."""

    schema: Mapping[str, Any]
    validate_value: Callable[[Any], T]

    @property
    def title(self) -> str | None:
        return self.schema.get("title")

    def validate(self, value: Any) -> T:
        """The validated result (a model instance for Python types).

        Raises:
            FormValidationError: With every issue found, not only the first.
        """
        return self.validate_value(value)

validate

validate(value: Any) -> T

The validated result (a model instance for Python types).

Raises:

Type Description
FormValidationError

With every issue found, not only the first.

Source code in src/promptantic/form/target.py
def validate(self, value: Any) -> T:
    """The validated result (a model instance for Python types).

    Raises:
        FormValidationError: With every issue found, not only the first.
    """
    return self.validate_value(value)

FormValidationError

Bases: ValueError

The finished value doesn't validate.

Source code in src/promptantic/form/target.py
class FormValidationError(ValueError):
    """The finished value doesn't validate."""

    def __init__(self, issues: list[Issue]) -> None:
        self.issues = issues
        super().__init__(
            "; ".join(f"{'/'.join(map(str, i.path)) or '<root>'}: {i.message}" for i in issues)
        )

Issue dataclass

One problem with a finished value, at a path into it ((): the whole value).

Source code in src/promptantic/form/target.py
@dataclass(frozen=True)
class Issue:
    """One problem with a finished value, at a path into it (``()``: the whole value)."""

    path: Path
    message: str

Meta dataclass

What every node carries besides its kind: labels, default, flags.

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True)
class Meta:
    """What every node carries besides its kind: labels, default, flags."""

    title: str | None = None
    description: str | None = None
    default: Any = UNSET
    """The schema's ``default``; :data:`UNSET` when it has none."""
    examples: tuple[Any, ...] = ()
    read_only: bool = False
    write_only: bool = False
    deprecated: bool = False
    extensions: Mapping[str, Any] = field(default_factory=dict)
    """``x-`` keys of the schema (e.g. ``x-completions``), without the prefix."""

    @property
    def has_default(self) -> bool:
        return self.default is not UNSET

default class-attribute instance-attribute

default: Any = UNSET

The schema's default; :data:UNSET when it has none.

extensions class-attribute instance-attribute

extensions: Mapping[str, Any] = field(default_factory=dict)

x- keys of the schema (e.g. x-completions), without the prefix.

NullNode dataclass

Bases: NodeBase

Only null (e.g. the None member of a union that isn't just "optional").

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True)
class NullNode(NodeBase):
    """Only ``null`` (e.g. the ``None`` member of a union that isn't just "optional")."""

    kind: Literal["null"] = "null"

NumberNode dataclass

Bases: NodeBase

A number; integer for whole numbers.

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True)
class NumberNode(NodeBase):
    """A number; ``integer`` for whole numbers."""

    kind: Literal["number"] = "number"
    integer: bool = False
    minimum: float | None = None
    maximum: float | None = None
    exclusive_minimum: float | None = None
    exclusive_maximum: float | None = None
    multiple_of: float | None = None

ObjectNode dataclass

Bases: NodeBase

Named fields, plus optionally free keys (additionalProperties with a schema).

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True, eq=False)
class ObjectNode(NodeBase):
    """Named fields, plus optionally free keys (``additionalProperties`` with a schema)."""

    kind: Literal["object"] = "object"
    build_properties: Callable[[], tuple[Property, ...]] | None = field(default=None, repr=False)
    build_additional: Callable[[], FormNode] | None = field(default=None, repr=False)
    """Schema of keys beyond the named ones; ``None``: no extra keys can be entered."""
    min_properties: int | None = None
    max_properties: int | None = None

    @cached_property
    def properties(self) -> tuple[Property, ...]:
        return () if self.build_properties is None else self.build_properties()

    @cached_property
    def additional(self) -> FormNode | None:
        """Node for the values of free keys, or ``None`` when there are none."""
        return None if self.build_additional is None else self.build_additional()

    @property
    def is_map(self) -> bool:
        """Only free keys (e.g. ``dict[str, int]``): a key/value editor."""
        return not self.properties and self.build_additional is not None

additional cached property

additional: FormNode | None

Node for the values of free keys, or None when there are none.

build_additional class-attribute instance-attribute

build_additional: Callable[[], FormNode] | None = field(default=None, repr=False)

Schema of keys beyond the named ones; None: no extra keys can be entered.

is_map property

is_map: bool

Only free keys (e.g. dict[str, int]): a key/value editor.

Property dataclass

One field of an :class:ObjectNode.

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True)
class Property:
    """One field of an :class:`ObjectNode`."""

    name: str
    node: FormNode
    required: bool
    title: str | None = None
    """The field's own title; the node's title may be that of a referenced schema."""

    @property
    def label(self) -> str:
        """The field's title, else its name as words (``ship_to`` -> ``Ship To``)."""
        return self.title or self.name.replace("_", " ").title()

label property

label: str

The field's title, else its name as words (ship_to -> Ship To).

title class-attribute instance-attribute

title: str | None = None

The field's own title; the node's title may be that of a referenced schema.

StringNode dataclass

Bases: NodeBase

Free text, optionally constrained.

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True)
class StringNode(NodeBase):
    """Free text, optionally constrained."""

    kind: Literal["string"] = "string"
    format: str | None = None
    """``date``, ``date-time``, ``email``, ``uri``, ``uuid``, ... (JSON Schema formats)."""
    min_length: int | None = None
    max_length: int | None = None
    pattern: str | None = None
    content_media_type: str | None = None

    @property
    def secret(self) -> bool:
        """Input that shouldn't be shown (``format: password`` or ``writeOnly``)."""
        return self.format == "password" or self.meta.write_only

format class-attribute instance-attribute

format: str | None = None

date, date-time, email, uri, uuid, ... (JSON Schema formats).

secret property

secret: bool

Input that shouldn't be shown (format: password or writeOnly).

TupleNode dataclass

Bases: NodeBase

A fixed sequence of positions, each of its own kind (prefixItems).

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True, eq=False)
class TupleNode(NodeBase):
    """A fixed sequence of positions, each of its own kind (``prefixItems``)."""

    kind: Literal["tuple"] = "tuple"
    build_positions: Callable[[], tuple[FormNode, ...]] | None = field(default=None, repr=False)

    @cached_property
    def positions(self) -> tuple[FormNode, ...]:
        return () if self.build_positions is None else self.build_positions()

UnionNode dataclass

Bases: NodeBase

One of several alternatives (anyOf / oneOf / several types).

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True, eq=False)
class UnionNode(NodeBase):
    """One of several alternatives (``anyOf`` / ``oneOf`` / several types)."""

    kind: Literal["union"] = "union"
    build_variants: Callable[[], tuple[Variant, ...]] | None = field(default=None, repr=False)
    discriminator: str | None = None
    """Property whose value tells the variants apart (OpenAPI / pydantic discriminator)."""

    @cached_property
    def variants(self) -> tuple[Variant, ...]:
        return () if self.build_variants is None else self.build_variants()

discriminator class-attribute instance-attribute

discriminator: str | None = None

Property whose value tells the variants apart (OpenAPI / pydantic discriminator).

Variant dataclass

One alternative of a :class:UnionNode.

Source code in src/promptantic/form/nodes.py
@dataclass(frozen=True)
class Variant:
    """One alternative of a :class:`UnionNode`."""

    label: str
    node: FormNode

build_form

build_form(schema: JsonSchema) -> FormNode

The form tree for schema (nested parts are built on first access).

Raises:

Type Description
SchemaError

The schema (or a $ref in it) can't be resolved.

Source code in src/promptantic/form/build.py
def build_form(schema: JsonSchema) -> FormNode:
    """The form tree for ``schema`` (nested parts are built on first access).

    Raises:
        SchemaError: The schema (or a ``$ref`` in it) can't be resolved.
    """
    return _node(schema, create_resolver(schema))

field_errors

field_errors(node: FormNode, value: Any) -> list[str]

What's wrong with value for this field alone (empty when it fits).

Covers the field's own constraints (length, pattern, format, bounds, item and key counts, allowed choices); the full document is validated at the end.

Source code in src/promptantic/form/values.py
def field_errors(node: FormNode, value: Any) -> list[str]:  # noqa: PLR0911
    """What's wrong with ``value`` for this field alone (empty when it fits).

    Covers the field's own constraints (length, pattern, format, bounds, item and
    key counts, allowed choices); the full document is validated at the end.
    """
    if value is None:
        return [] if node.nullable or node.kind in ("null", "any") else ["A value is required"]
    match node:
        case StringNode():
            return _string_errors(node, value)
        case NumberNode():
            return _number_errors(node, value)
        case ChoiceNode():
            allowed = [choice.value for choice in node.choices]
            return [] if value in allowed else ["Pick one of the options"]
        case ArrayNode():
            if not isinstance(value, list):
                return ["Expected a list"]
            errors = []
            if node.min_items is not None and len(value) < node.min_items:
                errors.append(f"At least {node.min_items} item(s)")
            if node.max_items is not None and len(value) > node.max_items:
                errors.append(f"At most {node.max_items} item(s)")
            if node.unique and len({json.dumps(item, sort_keys=True) for item in value}) < len(
                value
            ):
                errors.append("Items must be unique")
            return errors
        case ObjectNode():
            if not isinstance(value, dict):
                return ["Expected an object"]
            errors = [
                f"{prop.label} is required"
                for prop in node.properties
                if prop.required and prop.name not in value
            ]
            if node.min_properties is not None and len(value) < node.min_properties:
                errors.append(f"At least {node.min_properties} entries")
            if node.max_properties is not None and len(value) > node.max_properties:
                errors.append(f"At most {node.max_properties} entries")
            return errors
        case _:
            return []

initial_value

initial_value(node: FormNode) -> Any | Unset

The value a field starts with: its default, else :data:UNSET.

Source code in src/promptantic/form/values.py
def initial_value(node: FormNode) -> Any | Unset:
    """The value a field starts with: its default, else :data:`UNSET`."""
    return node.meta.default

parse_text

parse_text(node: StringNode | NumberNode | AnyNode, text: str) -> Any | Unset

The value typed text stands for; :data:UNSET for empty input.

Raises:

Type Description
FieldError

text isn't a number (number fields) or JSON (free fields).

Source code in src/promptantic/form/values.py
def parse_text(node: StringNode | NumberNode | AnyNode, text: str) -> Any | Unset:
    """The value typed ``text`` stands for; :data:`UNSET` for empty input.

    Raises:
        FieldError: ``text`` isn't a number (number fields) or JSON (free fields).
    """
    if text == "" and not (isinstance(node, StringNode) and node.min_length == 0):
        return UNSET
    match node:
        case StringNode():
            return text
        case NumberNode(integer=True):
            try:
                return int(text.strip().replace("_", ""))
            except ValueError:
                msg = "Enter a whole number"
                raise FieldError(msg) from None
        case NumberNode():
            try:
                number = float(text.strip().replace("_", ""))
            except ValueError:
                msg = "Enter a number"
                raise FieldError(msg) from None
            if not math.isfinite(number):
                msg = "Enter a finite number"
                raise FieldError(msg)
            return int(number) if number.is_integer() and "." not in text else number
        case AnyNode():
            try:
                return json.loads(text)
            except json.JSONDecodeError as exc:
                msg = f"Enter JSON ({exc.msg})"
                raise FieldError(msg) from None

target_for

target_for(target: type[T]) -> FormTarget[T]
target_for(target: Mapping[str, Any]) -> FormTarget[dict[str, Any]]
target_for(target: type[Any] | Mapping[str, Any]) -> FormTarget[Any]

The form target for a JSON Schema (as a mapping) or a Python type.

Source code in src/promptantic/form/target.py
def target_for(target: type[Any] | Mapping[str, Any]) -> FormTarget[Any]:
    """The form target for a JSON Schema (as a mapping) or a Python type."""
    if isinstance(target, Mapping):
        return _schema_target(target)
    return _type_target(target)