-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathserializer.py
More file actions
48 lines (38 loc) Β· 1.53 KB
/
serializer.py
File metadata and controls
48 lines (38 loc) Β· 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from __future__ import annotations
from typing import TypeVar, Type
from pydantic import BaseModel, ValidationError
from toon_format import encode, decode
T = TypeVar("T", bound="ToonPydanticModel")
class ToonPydanticModel(BaseModel):
"""
Pydantic mixin that adds TOON superpowers.
β’ schema_to_toon() β TOON schema string (for LLM few-shot / system prompts)
β’ from_toon() β Parse TOON output directly into validated model
"""
@classmethod
def schema_to_toon(cls) -> str:
"""
Convert the model's JSON schema into compact TOON format.
Use this in your LLM prompt to save 40β60% tokens vs JSON schema.
"""
schema = cls.model_json_schema()
# Pydantic gives us full JSON schema
return encode(schema)
@classmethod
def from_toon(cls: Type[T], text: str) -> T:
"""
Parse raw TOON string (from LLM) into a fully validated Pydantic model.
Raises:
ValueError β If TOON parsing fails
ValidationError β If data doesn't match model
ValueError β Friendly wrapper for both
"""
if not text.strip():
raise ValueError("Empty string cannot be parsed as TOON")
try:
data = decode(text.strip())
return cls.model_validate(data)
except ValidationError as e:
raise e # Let Pydantic's rich error surface (best UX)
except Exception as e:
raise ValueError(f"Failed to parse TOON into {cls.__name__}: {e}") from e