Skip to content

promptantic

Class info

Re-exported classes

Class Module Description
FieldSpec promptantic.model_spec One field of a model being designed.
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.
ModelCreator promptantic.creator Ask for a model's name and fields, and build the pydantic class.
ModelGenerator promptantic.generator Fill a pydantic model interactively; prefer :func:promptantic.fill.
ModelSpec promptantic.model_spec A model being designed: its name, description and fields.
PromptanticError promptantic.exceptions Base exception for promptantic.

🛈 DocStrings

Promptantic: main package.

Generate pydantic models using prompts.

FieldSpec

Bases: BaseModel

One field of a model being designed.

Source code in src/promptantic/model_spec.py
class FieldSpec(BaseModel):
    """One field of a model being designed."""

    # pydantic doesn't allow field names with a leading underscore
    name: str = Field(min_length=1, pattern=r"^[A-Za-z][A-Za-z0-9_]*$")
    type: FieldType = "string"
    required: bool = True
    default: str | None = Field(
        default=None, description="As you'd type it: 42, true, a text, or JSON for lists"
    )
    description: str | None = None
    items: ItemType = Field(default="string", description="Item type (for lists)")
    fields: list[FieldSpec] = Field(default=[], description="Its fields (for objects)")

    @field_validator("default")
    @classmethod
    def _check_default(cls, value: str | None, info: ValidationInfo) -> str | None:
        """Reject a default that isn't a value of the field's type (here, in the form)."""
        if value is not None and (kind := info.data.get("type")) is not None:
            _parse_default(kind, value)  # raises ValueError, shown at the field
        return value

    @field_validator("fields")
    @classmethod
    def _check_fields(cls, value: list[FieldSpec]) -> list[FieldSpec]:
        return _unique_names(value)

    def json_schema(self) -> dict[str, Any]:
        """The field as a JSON Schema property."""
        match self.type:
            case "list":
                schema: dict[str, Any] = {"type": "array", "items": dict(_SCHEMAS[self.items])}
            case "object":
                schema = _object_schema(self.fields)
            case kind:
                schema = dict(_SCHEMAS[kind])
        if self.description:
            schema["description"] = self.description
        if self.default is not None:
            schema["default"] = _parse_default(self.type, self.default)
        return schema

json_schema

json_schema() -> dict[str, Any]

The field as a JSON Schema property.

Source code in src/promptantic/model_spec.py
def json_schema(self) -> dict[str, Any]:
    """The field as a JSON Schema property."""
    match self.type:
        case "list":
            schema: dict[str, Any] = {"type": "array", "items": dict(_SCHEMAS[self.items])}
        case "object":
            schema = _object_schema(self.fields)
        case kind:
            schema = dict(_SCHEMAS[kind])
    if self.description:
        schema["description"] = self.description
    if self.default is not None:
        schema["default"] = _parse_default(self.type, self.default)
    return schema

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

ModelCreator

Ask for a model's name and fields, and build the pydantic class.

Source code in src/promptantic/creator.py
class ModelCreator:
    """Ask for a model's name and fields, and build the pydantic class."""

    async def acreate(
        self,
        model_name: str | None = None,
        base_classes: tuple[type[BaseModel], ...] = (BaseModel,),
    ) -> type[BaseModel]:
        """A new pydantic class, designed in a form.

        Raises:
            FormCancelledError: The user cancelled.
        """
        initial = {"name": model_name} if model_name else None
        spec = await fill(ModelSpec, title="New model", initial=initial)
        return spec.model_class(base=base_classes)

    async def acreate_instance(
        self,
        model_name: str | None = None,
        base_classes: tuple[type[BaseModel], ...] = (BaseModel,),
        populator: ModelGenerator | None = None,
    ) -> BaseModel:
        """Design a model, then fill an instance of it."""
        model: type[Any] = await self.acreate(model_name, base_classes)
        if populator is not None:
            return await populator.apopulate(model)
        return await fill(model)

acreate async

acreate(
    model_name: str | None = None, base_classes: tuple[type[BaseModel], ...] = (BaseModel,)
) -> type[BaseModel]

A new pydantic class, designed in a form.

Raises:

Type Description
FormCancelledError

The user cancelled.

Source code in src/promptantic/creator.py
async def acreate(
    self,
    model_name: str | None = None,
    base_classes: tuple[type[BaseModel], ...] = (BaseModel,),
) -> type[BaseModel]:
    """A new pydantic class, designed in a form.

    Raises:
        FormCancelledError: The user cancelled.
    """
    initial = {"name": model_name} if model_name else None
    spec = await fill(ModelSpec, title="New model", initial=initial)
    return spec.model_class(base=base_classes)

acreate_instance async

acreate_instance(
    model_name: str | None = None,
    base_classes: tuple[type[BaseModel], ...] = (BaseModel,),
    populator: ModelGenerator | None = None,
) -> BaseModel

Design a model, then fill an instance of it.

Source code in src/promptantic/creator.py
async def acreate_instance(
    self,
    model_name: str | None = None,
    base_classes: tuple[type[BaseModel], ...] = (BaseModel,),
    populator: ModelGenerator | None = None,
) -> BaseModel:
    """Design a model, then fill an instance of it."""
    model: type[Any] = await self.acreate(model_name, base_classes)
    if populator is not None:
        return await populator.apopulate(model)
    return await fill(model)

ModelGenerator

Fill a pydantic model interactively; prefer :func:promptantic.fill.

The constructor's options (style, show_progress, ...) belonged to the old prompt-per-type implementation and are accepted but ignored.

Source code in src/promptantic/generator.py
class ModelGenerator:
    """Fill a pydantic model interactively; prefer :func:`promptantic.fill`.

    The constructor's options (``style``, ``show_progress``, ...) belonged to the old
    prompt-per-type implementation and are accepted but ignored.
    """

    def __init__(self, *_args: Any, **_kwargs: Any) -> None:
        pass

    @overload
    async def apopulate[M: BaseModel](self, model: type[M]) -> M: ...
    @overload
    async def apopulate[M: BaseModel](self, model: M) -> M: ...
    async def apopulate[M: BaseModel](self, model: type[M] | M) -> M:
        """An instance of ``model``; given an instance, its values are the starting values."""
        if isinstance(model, BaseModel):
            return await fill(type(model), initial=initial_values(model))
        return await fill(model)

    @overload
    def populate[M: BaseModel](self, model: type[M]) -> M: ...
    @overload
    def populate[M: BaseModel](self, model: M) -> M: ...
    def populate[M: BaseModel](self, model: type[M] | M) -> M:
        """Like :meth:`apopulate`, for code that isn't async."""
        return asyncio.run(self.apopulate(model))

apopulate async

apopulate(model: type[M]) -> M
apopulate(model: M) -> M
apopulate(model: type[M] | M) -> M

An instance of model; given an instance, its values are the starting values.

Source code in src/promptantic/generator.py
async def apopulate[M: BaseModel](self, model: type[M] | M) -> M:
    """An instance of ``model``; given an instance, its values are the starting values."""
    if isinstance(model, BaseModel):
        return await fill(type(model), initial=initial_values(model))
    return await fill(model)

populate

populate(model: type[M]) -> M
populate(model: M) -> M
populate(model: type[M] | M) -> M

Like :meth:apopulate, for code that isn't async.

Source code in src/promptantic/generator.py
def populate[M: BaseModel](self, model: type[M] | M) -> M:
    """Like :meth:`apopulate`, for code that isn't async."""
    return asyncio.run(self.apopulate(model))

ModelSpec

Bases: BaseModel

A model being designed: its name, description and fields.

Source code in src/promptantic/model_spec.py
class ModelSpec(BaseModel):
    """A model being designed: its name, description and fields."""

    name: str = Field(min_length=1, pattern=r"^[A-Za-z_][A-Za-z0-9_]*$")
    description: str | None = None
    fields: list[FieldSpec] = Field(min_length=1)

    @field_validator("fields")
    @classmethod
    def _check_fields(cls, value: list[FieldSpec]) -> list[FieldSpec]:
        return _unique_names(value)

    def json_schema(self) -> dict[str, Any]:
        """The model as a JSON Schema object."""
        schema = {"title": self.name, **_object_schema(self.fields)}
        if self.description:
            schema["description"] = self.description
        return schema

    def model_class(
        self, *, base: type[BaseModel] | tuple[type[Any], ...] = BaseModel
    ) -> type[BaseModel]:
        """A pydantic class for the spec (nested objects become nested classes).

        Args:
            base: The base class, or several (a tuple, as for ``create_model``).
        """
        return _model_class(self.name, self.fields, base=base, doc=self.description)

json_schema

json_schema() -> dict[str, Any]

The model as a JSON Schema object.

Source code in src/promptantic/model_spec.py
def json_schema(self) -> dict[str, Any]:
    """The model as a JSON Schema object."""
    schema = {"title": self.name, **_object_schema(self.fields)}
    if self.description:
        schema["description"] = self.description
    return schema

model_class

model_class(*, base: type[BaseModel] | tuple[type[Any], ...] = BaseModel) -> type[BaseModel]

A pydantic class for the spec (nested objects become nested classes).

Parameters:

Name Type Description Default
base type[BaseModel] | tuple[type[Any], ...]

The base class, or several (a tuple, as for create_model).

BaseModel
Source code in src/promptantic/model_spec.py
def model_class(
    self, *, base: type[BaseModel] | tuple[type[Any], ...] = BaseModel
) -> type[BaseModel]:
    """A pydantic class for the spec (nested objects become nested classes).

    Args:
        base: The base class, or several (a tuple, as for ``create_model``).
    """
    return _model_class(self.name, self.fields, base=base, doc=self.description)

PromptanticError

Bases: Exception

Base exception for promptantic.

Source code in src/promptantic/exceptions.py
class PromptanticError(Exception):
    """Base exception for promptantic."""

fill async

fill(
    target: type[T] | FormTarget[T],
    *,
    title: str | None = None,
    initial: Mapping[str, Any] | None = None,
    ui: UI = "auto",
) -> T
fill(
    target: Mapping[str, Any],
    *,
    title: str | None = None,
    initial: Mapping[str, Any] | None = None,
    ui: UI = "auto",
) -> dict[str, Any]
fill(
    target: type[Any] | FormTarget[Any] | Mapping[str, Any],
    *,
    title: str | None = None,
    initial: Mapping[str, Any] | None = None,
    ui: UI = "auto",
) -> Any

Ask the user to fill a form and return the validated result.

Parameters:

Name Type Description Default
target type[Any] | FormTarget[Any] | Mapping[str, Any]

A JSON Schema (gives a dict), or a Python type such as a pydantic model or dataclass (gives an instance).

required
title str | None

Heading of the form (default: the schema's title).

None
initial Mapping[str, Any] | None

Starting values (default: the schema's defaults).

None
ui UI

textual (a form below the prompt), sequential (one prompt per field), or auto: textual when it's installed and the terminal is interactive.

'auto'

Raises:

Type Description
FormCancelledError

The user cancelled.

Source code in src/promptantic/api.py
async def fill(
    target: type[Any] | FormTarget[Any] | Mapping[str, Any],
    *,
    title: str | None = None,
    initial: Mapping[str, Any] | None = None,
    ui: UI = "auto",
) -> Any:
    """Ask the user to fill a form and return the validated result.

    Args:
        target: A JSON Schema (gives a dict), or a Python type such as a pydantic
            model or dataclass (gives an instance).
        title: Heading of the form (default: the schema's title).
        initial: Starting values (default: the schema's defaults).
        ui: ``textual`` (a form below the prompt), ``sequential`` (one prompt per field),
            or ``auto``: textual when it's installed and the terminal is interactive.

    Raises:
        FormCancelledError: The user cancelled.
    """
    form_target = target if isinstance(target, FormTarget) else target_for(target)
    if ui == "auto":
        ui = "textual" if _textual_usable() else "sequential"
    if ui == "textual":
        from promptantic.textual import fill_inline

        return await fill_inline(form_target, title=title, initial=initial)
    from promptantic.sequential import fill_sequential

    return await fill_sequential(form_target, title=title, initial=initial)

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)