Module

ai._structured

Structured output — LLM JSON responses to frozen dataclasses.

Generates JSON schema from dataclass fields and parses LLM responses back into typed instances. Same pattern as chirp.data row mapping — both produce frozen dataclasses from external data.

Functions

dataclass_to_schema 1 dict[str, Any]
Generate a JSON schema from a frozen dataclass. Used to instruct the LLM to re…
def dataclass_to_schema(cls: type[T]) -> dict[str, Any]

Generate a JSON schema from a frozen dataclass.

Used to instruct the LLM to return structured output matching the dataclass fields.

Supports: str, int, float, bool, list[str], list[int], list[float].

Parameters
Name Type Description
cls type[T]
Returns
dict[str, Any]
_type_to_schema 1 dict[str, Any]
Convert a Python type annotation to a JSON schema fragment.
def _type_to_schema(annotation: Any) -> dict[str, Any]
Parameters
Name Type Description
annotation Any
Returns
dict[str, Any]
parse_structured 2 T
Parse an LLM text response into a frozen dataclass. Extracts JSON from the res…
def parse_structured(cls: type[T], text: str) -> T

Parse an LLM text response into a frozen dataclass.

Extracts JSON from the response text (handles markdown code fences) and maps it to the dataclass fields.

Parameters
Name Type Description
cls type[T]
text str
Returns
T
_extract_json 1 str
Extract JSON from LLM text, handling markdown code fences.
def _extract_json(text: str) -> str
Parameters
Name Type Description
text str
Returns
str