Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

fix(structured): resolve local $defs refs so pydantic Enum fields become choices

sameedkhan17efa65d320999
diff --git a/docs/structured.md b/docs/structured.md
index 98391ec8..970053a4 100644
--- a/docs/structured.md
+++ b/docs/structured.md
@@ -42,7 +42,8 @@ The top level must be an object with `properties`. Each property becomes one que
Every row below is a real schema: `tests/test_structured_docs.py` compiles the first column and
asserts the question the compiler actually produces, so this table cannot drift from the code. A cell
-is either a property schema on its own, or a call to an entry point.
+is either a property schema on its own, a whole schema when the row needs its `$defs` (the field is
+named `field`), or a call to an entry point.
| JSON schema | Laya question | Returned value |
|---|---|---|
@@ -55,9 +56,14 @@ is either a property schema on its own, or a call to an entry point.
| `{"anyOf": [{"enum": ["x", "y"]}, {"type": "null"}]}` | `choice` | as the plain `enum` row; no answer leaves the key out |
| `{"oneOf": [{"type": "boolean"}, {"type": "null"}]}` | `noul` | as the plain `boolean` row |
| `{"type": ["integer", "null"], "minimum": 1, "maximum": 3}` | `score` | as the plain bounded-integer row |
+| `{"properties": {"field": {"$ref": "#/$defs/Dept"}}, "$defs": {"Dept": {"enum": ["billing", "support"]}}}` | `choice` | as the plain `enum` row; a local `$ref` is planned as the definition it names |
+| `{"allOf": [{"enum": ["x", "y"]}]}` | `choice` | as the plain `enum` row; the one-item wrapper pydantic v1 puts around a described `$ref` |
`Literal[...]` and `Optional[...]` are the pydantic spellings of the `enum` and `anyOf` rows:
-`questions_from_pydantic` renders them to those shapes and the same rows apply.
+`questions_from_pydantic` renders them to those shapes and the same rows apply. An `Enum` field
+(`str`/`int` mixins and `IntEnum` included) is the `$ref` row, which needs the whole schema to show:
+pydantic puts the members in `$defs` and points the property at them, so `Optional[Dept]` is an
+`anyOf` around that `$ref`.
`title` is **not** read. pydantic puts one on every field of `model_json_schema()` whether you asked
for it or not, and a per-property name cannot label the per-option choices a question is built from,
@@ -76,7 +82,7 @@ A schema that cannot be answered from a fixed option set raises `laya.structured
| `{"type": "string"}` | `properties.name: a free string cannot be a fixed option set; use 'enum' or a boolean` |
| `{"type": "array", "items": {"type": "string"}}` | `properties.name: arrays are not supported; ask one field per element` |
| `{"type": "object", "properties": {"inner": {"type": "boolean"}}}` | `properties.name: nested objects are not supported; flatten the schema` |
-| `{"$ref": "#/definitions/node"}` | `properties.name: $ref/recursion is not supported; flatten the schema` |
+| `{"$ref": "#/definitions/node"}` | `properties.name: $ref '#/definitions/node' does not resolve to an entry of this schema's '$defs' or 'definitions'` |
| `{"enum": [1, "1"]}` | `properties.name: enum values produce duplicate choice labels` |
| `{"enum": []}` | `properties.name: 'enum' must not be empty` |
| `{"type": "number"}` | `properties.name: a numeric field needs integer 'minimum' and 'maximum' to become a score` |
@@ -87,7 +93,8 @@ A schema that cannot be answered from a fixed option set raises `laya.structured
| `{"format": "date"}` | `properties.name: unsupported schema {'format': 'date'}` |
| `"boolean"` | `properties.name: property must be an object, got str` |
-The entry points themselves reject these:
+The entry points themselves reject these; the last row needs a whole schema, because a `$ref` cycle
+runs through its `$defs`:
| call | message |
|---|---|
@@ -97,6 +104,7 @@ The entry points themselves reject these:
| `plan_from_json_schema({"type": "object", "properties": {"p%d" % i: {"type": "boolean"} for i in range(33)}})` | `33 properties exceeds MAX_PROPERTIES=32` |
| `plan_from_json_schema({"type": "object", "properties": {"name": {"enum": ["v%d" % i for i in range(33)]}}})` | `properties.name: 33 options exceeds MAX_OPTIONS=32` |
| `decide(None, "I was charged twice.", schema=42)` | `expected a JSON schema dict or a pydantic model, got int` |
+| `plan_from_json_schema({"type": "object", "properties": {"name": {"$ref": "#/$defs/Loop"}}, "$defs": {"Loop": {"$ref": "#/$defs/Loop"}}})` | `properties.name: $ref '#/$defs/Loop' is recursive; flatten the schema` |
Limits: `MAX_PROPERTIES = 32`, `MAX_OPTIONS = 32`, `MAX_SCORE_LEVELS = 10`.
@@ -202,6 +210,14 @@ gate and the eval harness both use.
- A `description` becomes the question instructions, so a good description is what makes the
decision accurate. This follows the same rule as the [hooks guide](hooks/index.md): be explicit
about what each option means.
+- A local `$ref` (`#/$defs/...` or `#/definitions/...`) is replaced by the definition it names
+ before the field is planned, so a pydantic `Enum` asks exactly the question the matching `Literal`
+ asks and projects to the member's value, which `answer_to_pydantic` turns back into the member.
+ The property's own keys sit on top and the definition's `description` is dropped: pydantic fills
+ it from the enum's docstring (pydantic v1 with "An enumeration." when there is none), which
+ describes the type rather than the question, so the wording is still the field's `description`.
+ A ref to another document, a missing entry or a cycle raises, and a ref to a model is a nested
+ object.
- A `null` branch is dropped before the field is planned, so `Optional[X]` asks exactly the question
`X` asks. The field's key is simply absent from the values when there is no answer for it, which is
what makes it safe to declare a field optional without changing what the model sees.
diff --git a/laya/structured.py b/laya/structured.py
index e4cd512a..01130d40 100644
--- a/laya/structured.py
+++ b/laya/structured.py
@@ -142,9 +142,44 @@ def _score_field(path: str, name: str, prop: Dict[str, Any],
return _Field(name=name, kind="score", question=question, minimum=lo)
-def _field(path: str, name: str, prop: Dict[str, Any]) -> _Field:
+_LOCAL_REFS = (("#/$defs/", "$defs"), ("#/definitions/", "definitions"))
+
+
+def _inline_ref(path: str, prop: Dict[str, Any], root: Dict[str, Any],
+ seen: Tuple[str, ...]) -> Tuple[Dict[str, Any], Tuple[str, ...]]:
+ """Replace a local `$ref` with the definition it names, the property's own keys on top.
+
+ Pydantic renders every `Enum` field as `{"$ref": "#/$defs/<Name>"}` (draft-07 and pydantic v1
+ spell it `#/definitions/`), with a sibling `description` when the field has one. The
+ definition's own `description` is dropped: pydantic fills it from the enum's docstring (v1 with
+ "An enumeration." when there is none), which describes the type rather than asking about this
+ field, so the wording stays the field's and an `Enum` asks what the same `Literal` would. Only
+ this schema's own definitions are looked up; anything else is rejected rather than fetched, and
+ a ref met twice on one path is a cycle.
+ """
+ ref = prop["$ref"]
+ if ref in seen:
+ raise SchemaError("%s: $ref %r is recursive; flatten the schema" % (path, ref))
+ target = None
+ for prefix, key in _LOCAL_REFS:
+ defs = root.get(key)
+ if isinstance(ref, str) and ref.startswith(prefix) and isinstance(defs, dict):
+ target = defs.get(ref[len(prefix):])
+ if not isinstance(target, dict):
+ raise SchemaError("%s: $ref %r does not resolve to an entry of this schema's '$defs' or "
+ "'definitions'" % (path, ref))
+ # a `$ref` the definition carries is an alias, followed by the caller's loop
+ merged = {k: v for k, v in target.items() if k != "description"}
+ merged.update((k, v) for k, v in prop.items() if k != "$ref")
+ return merged, seen + (ref,)
+
+
+def _field(path: str, name: str, prop: Dict[str, Any], root: Optional[Dict[str, Any]] = None,
+ seen: Tuple[str, ...] = ()) -> _Field:
if not isinstance(prop, dict):
raise SchemaError("%s: property must be an object, got %s" % (path, type(prop).__name__))
+ while "$ref" in prop:
+ prop, seen = _inline_ref(path, prop, root or {}, seen)
description = prop.get("description")
# Pydantic v2 renders `Optional[X]` as `{"anyOf": [<X>, {"type": "null"}]}` with no
# top-level type/enum/const, the same nullable shape the list form `type: ["string", "null"]`
@@ -152,6 +187,13 @@ def _field(path: str, name: str, prop: Dict[str, Any]) -> _Field:
# so `Optional[Literal[...]]`, `Optional[int]` and friends map instead of raising. A union of
# two real types is genuinely ambiguous and still rejected.
if not ({"const", "enum", "type"} & set(prop)):
+ # pydantic v1 wraps a described `$ref` as `{"allOf": [{"$ref": ...}], "description": ...}`;
+ # a one-item `allOf` is that schema, so it is unwrapped too, the outer keys on top.
+ wrapped = prop.get("allOf")
+ if isinstance(wrapped, list) and len(wrapped) == 1 and isinstance(wrapped[0], dict):
+ branch = dict(wrapped[0])
+ branch.update((k, v) for k, v in prop.items() if k != "allOf")
+ return _field(path, name, branch, root, seen)
union = prop.get("anyOf") or prop.get("oneOf")
if union is not None:
branches = [b for b in union if isinstance(b, dict) and b.get("type") != "null"]
@@ -161,7 +203,7 @@ def _field(path: str, name: str, prop: Dict[str, Any]) -> _Field:
% (path, len(branches)))
branch = dict(branches[0])
branch.setdefault("description", description)
- return _field(path, name, branch)
+ return _field(path, name, branch, root, seen)
if "const" in prop:
return _enum_field(path, name, [prop["const"]], description)
if "enum" in prop:
@@ -184,8 +226,6 @@ def _field(path: str, name: str, prop: Dict[str, Any]) -> _Field:
raise SchemaError("%s: arrays are not supported; ask one field per element" % path)
if jtype == "object":
raise SchemaError("%s: nested objects are not supported; flatten the schema" % path)
- if "$ref" in prop:
- raise SchemaError("%s: $ref/recursion is not supported; flatten the schema" % path)
raise SchemaError("%s: unsupported schema %r" % (path, prop))
@@ -200,7 +240,7 @@ def plan_from_json_schema(schema: Dict[str, Any]) -> List[_Field]:
raise SchemaError("'properties' must be a non-empty object")
if len(properties) > MAX_PROPERTIES:
raise SchemaError("%d properties exceeds MAX_PROPERTIES=%d" % (len(properties), MAX_PROPERTIES))
- return [_field("properties.%s" % name, name, prop) for name, prop in properties.items()]
+ return [_field("properties.%s" % name, name, prop, schema) for name, prop in properties.items()]
def questions_from_json_schema(schema: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
diff --git a/tests/test_structured.py b/tests/test_structured.py
index ccda8890..31018efb 100644
--- a/tests/test_structured.py
+++ b/tests/test_structured.py
@@ -474,6 +474,149 @@ check_raises("nullable/two real branches rejected", SchemaError,
"properties": {"a": {"anyOf": [{"type": "boolean"}, {"type": "integer"}]}}}))
+# --------------------------------------------------------------- local $ref (pydantic Enum)
+# Pydantic renders every `Enum` field as `{"$ref": "#/$defs/<Name>"}` (v1 and draft-07 use
+# `#/definitions/`, and wrap a described ref in a one-item `allOf`), so a local ref to an enum
+# definition must plan as the enum it points at, with the property's own keys kept on top.
+def _schema_with_defs(props, key="$defs"):
+ return {"type": "object", "properties": props, key: {
+ "Dept": {"enum": ["billing", "support"], "type": "string", "title": "Dept",
+ "description": "The team that owns it."},
+ "Prio": {"enum": [0, 1, 2], "type": "integer", "title": "Prio"},
+ "Alias": {"$ref": "#/%s/Prio" % key},
+ "Node": {"type": "object", "properties": {"next": {"$ref": "#/%s/Node" % key}}},
+ "Loop": {"$ref": "#/%s/Loop" % key},
+ "Maybe": {"anyOf": [{"$ref": "#/%s/Maybe" % key}, {"type": "null"}]},
+ }}
+
+
+def _ref_error(prop, key="$defs"):
+ try:
+ plan_from_json_schema(_schema_with_defs({"a": prop}, key))
+ except SchemaError as exc:
+ return str(exc)
+ return None
+
+
+REFS = _schema_with_defs({
+ "dept": {"$ref": "#/$defs/Dept"},
+ "described": {"$ref": "#/$defs/Dept", "description": "Which team?"},
+ "optional": {"anyOf": [{"$ref": "#/$defs/Dept"}, {"type": "null"}], "default": None,
+ "description": "Which team, if any?"},
+ "wrapped": {"allOf": [{"$ref": "#/$defs/Dept"}], "description": "Which team (v1)?"},
+ "prio": {"$ref": "#/$defs/Prio", "default": 0},
+ "alias": {"$ref": "#/$defs/Alias"},
+})
+rq = questions_from_json_schema(REFS)
+check("ref/enum definition is a choice", rq["dept"]["type"], "choice")
+check("ref/enum labels come from the definition", list(rq["dept"]["criteria"]), ["billing", "support"])
+# The definition's description is pydantic's copy of the enum docstring ("An enumeration." on v1
+# when there is none): it describes the type, not this field, so it is not the question wording.
+check("ref/definition's own description is not the wording", rq["dept"]["instructions"],
+ "What is `dept`?")
+check("ref/sibling description is the wording", rq["described"]["instructions"], "Which team?")
+check("ref/Optional ref is a choice", rq["optional"]["type"], "choice")
+check("ref/Optional ref carries the outer description", rq["optional"]["instructions"], "Which team, if any?")
+check("ref/allOf-wrapped ref is a choice", rq["wrapped"]["type"], "choice")
+check("ref/allOf-wrapped ref keeps the sibling description", rq["wrapped"]["instructions"], "Which team (v1)?")
+check("ref/integer enum labels", list(rq["prio"]["criteria"]), ["0", "1", "2"])
+check("ref/a ref to a ref resolves", list(rq["alias"]["criteria"]), ["0", "1", "2"])
+check("ref/draft-07 #/definitions/ resolves",
+ questions_from_json_schema(_schema_with_defs({"a": {"$ref": "#/definitions/Dept"}}, "definitions"))
+ ["a"]["type"], "choice")
+check("ref/allOf wraps an inline schema too",
+ questions_from_json_schema({"type": "object", "properties": {"a": {"allOf": [{"type": "boolean"}]}}})
+ ["a"]["type"], "noul")
+rv = answers_to_json({"dept": {"choice": "support"}, "prio": {"choice": "2"}, "alias": {"choice": "1"}}, REFS)
+check("ref/projects the definition's values", rv, {"dept": "support", "prio": 2, "alias": 1})
+_before = repr(REFS)
+plan_from_json_schema(REFS)
+check("ref/planning does not mutate the schema", repr(REFS), _before)
+
+check("ref/missing definition is rejected", _ref_error({"$ref": "#/$defs/Nope"}),
+ "properties.a: $ref '#/$defs/Nope' does not resolve to an entry of this schema's '$defs' or 'definitions'")
+check("ref/wrong definitions key is rejected", _ref_error({"$ref": "#/definitions/Dept"}),
+ "properties.a: $ref '#/definitions/Dept' does not resolve to an entry of this schema's '$defs' or "
+ "'definitions'")
+check("ref/non-local ref is rejected", _ref_error({"$ref": "other.json#/$defs/Dept"}),
+ "properties.a: $ref 'other.json#/$defs/Dept' does not resolve to an entry of this schema's '$defs' or "
+ "'definitions'")
+check("ref/a ref with no definitions at all is rejected", _ref_error({"$ref": "#/$defs/X"}, "unused"),
+ "properties.a: $ref '#/$defs/X' does not resolve to an entry of this schema's '$defs' or 'definitions'")
+check("ref/self-reference is rejected", _ref_error({"$ref": "#/$defs/Loop"}),
+ "properties.a: $ref '#/$defs/Loop' is recursive; flatten the schema")
+check("ref/recursion through Optional is rejected", _ref_error({"$ref": "#/$defs/Maybe"}),
+ "properties.a: $ref '#/$defs/Maybe' is recursive; flatten the schema")
+check("ref/an object definition is a nested object", _ref_error({"$ref": "#/$defs/Node"}),
+ "properties.a: nested objects are not supported; flatten the schema")
+
+try:
+ import enum
+ from typing import Optional
+
+ import pydantic
+
+ class Dept(str, enum.Enum):
+ billing = "billing"
+ support = "support"
+ sales = "sales"
+
+ class Prio(enum.IntEnum):
+ low = 0
+ high = 1
+
+ class Colour(enum.Enum):
+ red = "red"
+ blue = "blue"
+
+ class EnumTicket(pydantic.BaseModel):
+ department: Dept = pydantic.Field(description="Which team should handle this?")
+ prio: Prio
+ colour: Colour
+ backup: Optional[Dept] = None
+
+ eq = questions_from_pydantic(EnumTicket)
+ check("pydantic-enum/str Enum is a choice", eq["department"]["type"], "choice")
+ check("pydantic-enum/Field description is the wording", eq["department"]["instructions"],
+ "Which team should handle this?")
+ check("pydantic-enum/labels are the member values", list(eq["department"]["criteria"]),
+ ["billing", "support", "sales"])
+ check("pydantic-enum/IntEnum is a choice", (eq["prio"]["type"], list(eq["prio"]["criteria"])),
+ ("choice", ["0", "1"]))
+ check("pydantic-enum/plain Enum is a choice", eq["colour"]["type"], "choice")
+ check("pydantic-enum/Optional[Enum] is a choice", eq["backup"]["type"], "choice")
+
+ enum_answers = {
+ "department": {"type": "choice", "choice": "support", "confidence": 0.9, "probabilities": {}},
+ "prio": {"type": "choice", "choice": "1", "confidence": 0.8, "probabilities": {}},
+ "colour": {"type": "choice", "choice": "blue", "confidence": 0.8, "probabilities": {}},
+ }
+ et = answer_to_pydantic(EnumTicket, enum_answers)
+ check("pydantic-enum/round trip to members", (et.department, et.prio, et.colour, et.backup),
+ (Dept.support, Prio.high, Colour.blue, None))
+ check_true("pydantic-enum/IntEnum comes back as the member", et.prio is Prio.high)
+ et = answer_to_pydantic(EnumTicket, dict(enum_answers, backup={"type": "choice", "choice": "sales"}))
+ check("pydantic-enum/Optional[Enum] answered", et.backup, Dept.sales)
+ check("pydantic-enum/decide projects values",
+ decide(FakeRunner(enum_answers), "s", schema=EnumTicket),
+ {"department": "support", "prio": 1, "colour": "blue"})
+
+ class Inner(pydantic.BaseModel):
+ flag: bool
+
+ class Outer(pydantic.BaseModel):
+ inner: Inner
+
+ try:
+ questions_from_pydantic(Outer)
+ FAIL.append("pydantic-enum/nested model: did not raise")
+ except SchemaError as exc:
+ check("pydantic-enum/nested model is still a nested object", str(exc),
+ "properties.inner: nested objects are not supported; flatten the schema")
+except ImportError:
+ PASS.append("pydantic-enum/skipped (not installed)")
+
+
print("\n%d passed, %d failed" % (len(PASS), len(FAIL)))
for f in FAIL:
print(" FAIL", f)
diff --git a/tests/test_structured_docs.py b/tests/test_structured_docs.py
index b25a9cb5..1488338d 100644
--- a/tests/test_structured_docs.py
+++ b/tests/test_structured_docs.py
@@ -288,13 +288,13 @@ def main() -> int:
api = parse_table(text, API_HEADER)
# ------------------------------------------------------------------ the tables parsed at all
- check_true("subset table/parsed rows", len(subset) == 9, "got %d" % len(subset))
+ check_true("subset table/parsed rows", len(subset) == 11, "got %d" % len(subset))
check_true("subset table/every row has three cells",
all(len(r) == 3 for r in subset), [len(r) for r in subset])
check_true("rejections table/parsed rows", len(props) == 13, "got %d" % len(props))
check_true("rejections table/every row has two cells",
all(len(r) == 2 for r in props), [len(r) for r in props])
- check_true("entry point table/parsed rows", len(calls) == 6, "got %d" % len(calls))
+ check_true("entry point table/parsed rows", len(calls) == 7, "got %d" % len(calls))
check_true("api table/parsed rows", len(api) >= 6, "got %d" % len(api))
# ----------------------------------------------------------- the subset table, row by row
@@ -311,10 +311,14 @@ def main() -> int:
FAIL.append("subset row/%s: a schema cell must be an object, got %s"
% (row[0], type(prop).__name__))
continue
+ # a `$ref` row is a whole schema, because what it points at lives in the schema's `$defs`
+ if "properties" in prop:
+ schema, prop = prop, prop["properties"]["field"]
+ else:
+ schema = {"type": "object", "properties": {"field": prop}}
documented_keys.update(prop.keys())
try:
- field = S.plan_from_json_schema(
- {"type": "object", "properties": {"field": prop}})[0]
+ field = S.plan_from_json_schema(schema)[0]
except Exception as exc:
FAIL.append("subset row/%s: the documented schema raises %s: %s"
% (row[0], type(exc).__name__, exc))