teff.schema¶
teff.schema
¶
Lightweight JSON Schema validation for structured LLM output.
Constitution Principle VI: minimal dependencies. This module provides a
compact JSON Schema subset — objects, arrays, primitives, enum,
oneOf, and string/number limits — implemented with stdlib only, so
no jsonschema or Pydantic dependency is required.
The subset covers the practical shapes an LLM is asked to produce:
{"type": "object", "properties": {...}, "required": [...]}{"type": "array", "items": {...}, "minItems"/"maxItems"}- primitives with
enum,minimum/maximum,minLength/maxLength/pattern oneOf/anyOffor unions and nullable fields (both are treated as alternative branches, so schemas produced by Pydantic'smodel_json_schema()— which emitsanyOfforOptional— validate as expected)
Functions:
| Name | Description |
|---|---|
extract_json_object |
Return the balanced JSON object starting at |
json_schema_from_type |
Build a JSON Schema from a Python type spec. |
parse_json_object |
Extract and parse a JSON value from LLM output. |
validate_json |
Validate value against schema. |
extract_json_object
¶
extract_json_object(text, start)
Return the balanced JSON object starting at text[start] == '{'.
Source code in teff/schema.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
json_schema_from_type
¶
json_schema_from_type(spec)
Build a JSON Schema from a Python type spec.
Accepts:
- a raw JSON Schema dict (returned unchanged);
- a
dict[str, type]field map, e.g.{"name": str, "age": int}; - a
TypedDict(or dataclass) class whose fields becomeproperties.
Raises:
| Type | Description |
|---|---|
TypeError
|
If spec is none of the supported forms. |
Source code in teff/schema.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | |
parse_json_object
¶
parse_json_object(content)
Extract and parse a JSON value from LLM output.
Tries json.loads on the whole text first, then falls back to the
first balanced {...} object embedded in surrounding prose (a
common failure mode for local models).
Returns:
| Type | Description |
|---|---|
Any
|
The parsed value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no valid JSON can be found in content. |
Source code in teff/schema.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
validate_json
¶
validate_json(value, schema)
Validate value against schema.
Returns:
| Type | Description |
|---|---|
list[str]
|
A list of human-readable error strings. An empty list means the |
list[str]
|
value conforms to the schema. |
Source code in teff/schema.py
56 57 58 59 60 61 62 63 64 65 | |