yr.Struct

Inherits: BaseModel
Subclasses: Condition

Base class for structured-generation specs.

Subclass Struct to declare the shape of a value the LLM should produce, then call fill on the subclass to generate a populated instance from a prompt.

Unknown fields are rejected at construction time: structs are intended to be fixed in structure, separating data (the struct) from behaviour (defined elsewhere). Passing fields not declared on the subclass raises a ValidationError.

Examples

Extract structured information from a short biography:

python
import yera as yr

class Person(yr.Struct):
    name: str
    age: int
    occupation: str

biography = "Dr. John Smith is a 36-year-old data scientist."

person = Person.fill(instruction=f"Extract details from: {biography}")

Methods

__init_subclass__ — Initialize a struct subclass and normalize its annotations.
expects_result — Return whether this struct expects an LLM result.
get_tool_name — Return the tool name used when calling the LLM.
get_call_id — Return the stored tool call ID, or raise if unset.
set_call_id — Set the tool call ID for this struct instance.
fill — Generate an instance of this struct from a prompt.
form — Ask the user to fill in this struct as a form.
__hash__ — Hash by field values, recursively freezing containers.
model_json_schema — Return the JSON schema for this struct with extra strictness applied.

Struct.__init_subclass__

__init_subclass__(
    expects_result: bool = False,
    **kwargs,
) → None

Initialize a struct subclass and normalize its annotations.

Parameters

expects_result
type: bool = False

Whether instances are expected as LLM tool results.

**kwargs
type: Unpack[ConfigDict]

Pydantic model configuration inherited by the subclass.

Struct.expects_result

expects_result() → bool

Return whether this struct expects an LLM result.

Returns

type: bool

Whether the struct is configured as a result type.

Struct.get_tool_name

get_tool_name() → str

Return the tool name used when calling the LLM.

Returns

type: str

The struct class name.

Struct.get_call_id

get_call_id() → str

Return the stored tool call ID, or raise if unset.

Returns

type: str

The call ID string assigned via set_call_id.

Raises

ValueError

If no call ID has been set (__call_id__ is None).

Struct.set_call_id

set_call_id(
    call_id: str,
) → None

Set the tool call ID for this struct instance.

Parameters

call_id
type: str

String identifier assigned by the LLM tool-calling API.

Struct.fill

fill(
    instruction: str | None = None,
    on_wire: bool = False,
    **kwargs,
) → Self

Generate an instance of this struct from a prompt.

Sends the prompt to the active LLM and parses its response into an instance of the calling subclass.

Parameters

instruction
type: str | None = None

Optional instruction describing the value to generate.

on_wire
type: bool = False

Whether the generated structured response should remain in the conversation sent with later model requests.

**kwargs
type: str | int | float | bool

Provider-specific generation options forwarded to the active LLM, such as temperature.

Returns

type: Self

An instance of the calling subclass, populated from the LLM's response.

Examples

Generate a structured fact with explicit model controls:

python
import yera as yr

class CountryFact(yr.Struct):
    country: str
    capital: str
    population: int

fact = CountryFact.fill(
    instruction="Describe Spain.",
    on_wire=True,
    temperature=0,
)

Struct.form

form(
    label: str | None = None,
    cancel_label: str | None = None,
) → Self | None

Ask the user to fill in this struct as a form.

Each field is presented with a widget suited to its type. Submissions that fail validation are shown again with their errors until one is valid or the user cancels.

Parameters

label
type: str | None = None

Optional question shown above the form.

cancel_label
type: str | None = None

Optional label for an action that returns None without validating the form.

Returns

type: Self | None

An instance built from the accepted submission, or None when cancellation is enabled and selected.

Examples

Present a form that the user may leave without submitting:

python
import yera as yr

class TripRequest(yr.Struct):
    destination: str
    travellers: int = 1

request = TripRequest.form(
    "Plan a trip",
    cancel_label="Not now",
)

if request is None:
    yr.markdown("No trip was planned.")

Struct.__hash__

__hash__() → int

Hash by field values, recursively freezing containers.

Allows Struct instances to be used as members in hashable containers and as dict keys. Mutating fields after hashing will make the instance unfindable in the collection; treat hashed structs as immutable.

Returns

type: int

A hash derived recursively from the struct's field values.

Struct.model_json_schema

model_json_schema(
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = _StrictSchema,
    mode: JsonSchemaMode = 'validation',
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) → dict

Return the JSON schema for this struct with extra strictness applied.

Overridden to ensure all nested objects have additionalProperties: false.

Parameters

by_alias
type: bool = True

Whether field aliases should be used as schema keys.

ref_template
type: str = DEFAULT_REF_TEMPLATE

Template used for generated schema references.

schema_generator
type: type[GenerateJsonSchema] = _StrictSchema

JSON Schema generator implementation.

mode
type: JsonSchemaMode = 'validation'

Whether to generate validation or serialization schema.

union_format
type: Literal['any_of', 'primitive_type_array'] = 'any_of'

Representation used for primitive unions.

Returns

type: dict

A JSON schema dict with additionalProperties: false for all objects.