-
Notifications
You must be signed in to change notification settings - Fork 58
feat(pydantic): add ToonPydanticModel with schema_to_toon() and from_toon() #46
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
alesanfra
merged 3 commits into
toon-format:main
from
Ansarafsar:feat/pydantic-integration
May 20, 2026
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
4d80639
feat(pydantic): add ToonPydanticModel with schema_to_toon() and from_…
Ansarafsar c0edb96
feat(pydantic): enhance ToonPydanticModel with model_dump_toon() and …
Ansarafsar 9c9b5cf
feat(pydantic): update type hints in ToonPydanticModel and tests for …
Ansarafsar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| from .serializer import ToonPydanticModel | ||
|
|
||
| __all__ = ["ToonPydanticModel"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,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 | ||
|
Ansarafsar marked this conversation as resolved.
Outdated
|
||
| """ | ||
|
|
||
| @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: | ||
|
Ansarafsar marked this conversation as resolved.
Outdated
|
||
| """ | ||
| 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import pytest | ||
| from pydantic import BaseModel, ValidationError | ||
|
|
||
| from toon_format.pydantic import ToonPydanticModel | ||
|
|
||
|
|
||
| class User(ToonPydanticModel): | ||
| name: str | ||
| age: int | ||
| email: str | None = None | ||
|
|
||
|
|
||
| def test_schema_to_toon(): | ||
| schema = User.schema_to_toon() | ||
| assert "name:str" in schema | ||
| assert "age:int" in schema | ||
| assert "email:" in schema # optional field | ||
|
|
||
|
|
||
| def test_from_toon_success(): | ||
| toon = "name:Ansar\nage:25\nemail:null" | ||
| user = User.from_toon(toon) | ||
| assert user.name == "Ansar" | ||
| assert user.age == 25 | ||
| assert user.email is None | ||
|
|
||
|
|
||
| def test_from_toon_validation_error(): | ||
| toon = "name:Ansar\nage:twenty-five" # wrong type | ||
| with pytest.raises(ValidationError): | ||
| User.from_toon(toon) | ||
|
|
||
|
|
||
| def test_from_toon_empty_string(): | ||
| with pytest.raises(ValueError, match="Empty string"): | ||
| User.from_toon("") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.