|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TypeVar |
| 4 | + |
| 5 | +from pydantic import BaseModel, ValidationError |
| 6 | + |
| 7 | +from toon_format import decode, encode |
| 8 | + |
| 9 | +T = TypeVar("T", bound="ToonPydanticModel") |
| 10 | + |
| 11 | + |
| 12 | +class ToonPydanticModel(BaseModel): |
| 13 | + """ |
| 14 | + Pydantic mixin that adds TOON superpowers. |
| 15 | +
|
| 16 | + • schema_to_toon() → TOON schema string (for LLM few-shot / system prompts) |
| 17 | + • model_dump_toon() → Serialize this model instance to a TOON string |
| 18 | + • model_validate_toon() → Parse TOON output directly into a validated model |
| 19 | + """ |
| 20 | + |
| 21 | + @classmethod |
| 22 | + def schema_to_toon(cls) -> str: |
| 23 | + """ |
| 24 | + Convert the model's JSON schema into compact TOON format. |
| 25 | + Use this in your LLM prompt to save 40–60% tokens vs JSON schema. |
| 26 | + """ |
| 27 | + schema = cls.model_json_schema() |
| 28 | + # Pydantic gives us full JSON schema |
| 29 | + return encode(schema) |
| 30 | + |
| 31 | + def model_dump_toon(self, **kwargs) -> str: |
| 32 | + """ |
| 33 | + Serialize this model instance into a compact TOON string. |
| 34 | +
|
| 35 | + Mirrors pydantic's ``model_dump_json()``. Extra keyword arguments are |
| 36 | + forwarded to ``model_dump()`` (e.g. ``exclude_none=True``). |
| 37 | + """ |
| 38 | + data = self.model_dump(mode="json", **kwargs) |
| 39 | + return encode(data) |
| 40 | + |
| 41 | + @classmethod |
| 42 | + def model_validate_toon(cls: type[T], text: str) -> T: |
| 43 | + """ |
| 44 | + Parse a raw TOON string (from an LLM) into a fully validated model. |
| 45 | +
|
| 46 | + Mirrors pydantic's ``model_validate_json()``. |
| 47 | +
|
| 48 | + Raises: |
| 49 | + ValueError – If TOON parsing fails or the input is empty |
| 50 | + ValidationError – If data doesn't match the model |
| 51 | + """ |
| 52 | + if not text.strip(): |
| 53 | + raise ValueError("Empty string cannot be parsed as TOON") |
| 54 | + |
| 55 | + try: |
| 56 | + data = decode(text.strip()) |
| 57 | + return cls.model_validate(data) |
| 58 | + except ValidationError as e: |
| 59 | + raise e # Let Pydantic's rich error surface (best UX) |
| 60 | + except Exception as e: |
| 61 | + raise ValueError(f"Failed to parse TOON into {cls.__name__}: {e}") from e |
0 commit comments