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.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
fix(integrations): fail closed on malformed nested decision fields
thread3d4c0203767f43
diff --git a/laya/integrations/_guard.py b/laya/integrations/_guard.pyindex 892dacac..e5bdb475 100644--- a/laya/integrations/_guard.py+++ b/laya/integrations/_guard.py@@ -1,5 +1,6 @@-"""The score-question rule shared by the guardrail wrappers."""-from typing import Any, Dict+"""The score-question rule, and the answer-shape checks, shared by the guardrail wrappers."""+import math+from typing import Any, Dict, Iterable, Optionaldef score_violation_probability(answer: Dict[str, Any], levels: int = 0) -> float:@@ -46,3 +47,73 @@ def score_violation_probability(answer: Dict[str, Any], levels: int = 0) -> floaif isinstance(score, bool) or not isinstance(score, (int, float)):return 0.0return score / (k - 1)+++#: The error every wrapper raises for a decision body it cannot read. Kept in one place so the+#: message a caller sees does not depend on which adapter they wired up.+MALFORMED_PREFIX = "Malformed decision response"+++def malformed(where: str, what: str) -> RuntimeError:+ """The error an adapter raises for a body field it cannot read, in one wording."""+ return RuntimeError("%s from %s: %s" % (MALFORMED_PREFIX, where, what))+++def answers_map(result: Any, where: str = "Laya") -> Dict[str, Dict[str, Any]]:+ """The `answers` mapping of a decision result, refusing anything that is not one.++ A remote decision body is arbitrary JSON, and every consumer in this package reads it as+ ``res.get("answers", {})`` and then indexes into it. The ``{}`` default only fires when the key+ is ABSENT: a body carrying ``{"answers": []}``, or an answer that is a string or ``null``, is+ handed back verbatim and the next call raises ``AttributeError``/``TypeError`` *out of the path+ whose whole job is to fail closed*. `tools.py` already refuses that shape and routes to its+ fallback tool; the guardrail wrappers had no guard at all.++ Both layers are checked here, once, so the adapters cannot drift from each other.+ """+ answers = result.get("answers", {}) if isinstance(result, dict) else None+ if not isinstance(answers, dict):+ raise RuntimeError(+ "%s from %s: 'answers' must be a JSON object, got %s"+ % (MALFORMED_PREFIX, where, type(answers).__name__))+ for qid, answer in answers.items():+ if not isinstance(answer, dict):+ raise RuntimeError(+ "%s from %s: the answer for %r must be a JSON object, got %s"+ % (MALFORMED_PREFIX, where, qid, type(answer).__name__))+ return answers+++def answer_number(answer: Dict[str, Any], field: str, where: str = "Laya",+ default: float = 0.0) -> float:+ """One numeric field of an answer as a usable float, or `RuntimeError`.++ `noul`, `score` and `confidence` ride the same arbitrary-body path as `probabilities`. A string+ or `None` raises `TypeError` inside the threshold comparison, which is the crash this refuses;+ a `bool` is refused too rather than read as 1.0/0.0 (`bool` subclasses `int`), because a+ spurious `true` would otherwise become a full-probability violation; and a non-finite value is+ refused because every comparison against NaN silently answers False, i.e. "safe".+ """+ value = answer.get(field, default)+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):+ raise RuntimeError(+ "%s from %s: %r must be a finite number, got %r"+ % (MALFORMED_PREFIX, where, field, value))+ return float(value)+++def probability_map(answer: Dict[str, Any], keys: Iterable[str], where: str = "Laya") -> Dict[str, float]:+ """`probabilities` restricted to `keys`, each a finite number, missing keys as 0.0.++ The multi-selector sorts and thresholds these values, so a mixed dict of numbers and strings+ raised `TypeError` from `sorted`, and a `true` ranked first as 1.0. Restricting to the caller's+ own keys also means an unknown extra key cannot win the ranking.+ """+ probs: Optional[Any] = answer.get("probabilities")+ if probs is None:+ probs = {}+ if not isinstance(probs, dict):+ raise RuntimeError(+ "%s from %s: 'probabilities' must be a JSON object, got %s"+ % (MALFORMED_PREFIX, where, type(probs).__name__))+ return {key: (answer_number(probs, key, where) if key in probs else 0.0) for key in keys}diff --git a/laya/integrations/agno.py b/laya/integrations/agno.pyindex 20dc6cc5..0f5b594b 100644--- a/laya/integrations/agno.py+++ b/laya/integrations/agno.py@@ -89,6 +89,9 @@ from ._controls import predict_kwargs as _predict_kwargs, reject_remote_hooks asfrom ._controls import reject_remote_lang_guess as _reject_remote_lang_guess # noqa: E402from ._controls import require_router_controls as _require_router_controls # noqa: E402from ._controls import router_kwargs as _router_kwargs # noqa: E402+from ._guard import answer_number as _answer_number # noqa: E402+from ._guard import answers_map as _answers_map # noqa: E402+from ._guard import malformed as _malformed # noqa: E402from ._guard import score_violation_probability as _score_violation_probability # noqa: E402from ..confidence import _gate_confidence # noqa: E402@@ -545,8 +548,14 @@ class LayaAgnoRouter:)self.last_decision = res- ans = res.get("answers", {}).get("delegation", {})+ # The same nested-shape checks as the guardrail screen: `answers` must be an object,+ # the answer must be an object, and `choice` is used with `.startswith` below -- a list+ # there raised AttributeError out of a routing decision.+ where = f"Laya server at {self.base_url}" if self.base_url else "Laya"+ ans = _answers_map(res, where).get("delegation", {})chosen_key = ans.get("choice")+ if chosen_key is not None and not isinstance(chosen_key, str):+ raise _malformed(where, "'choice' must be a string, got %s" % type(chosen_key).__name__)# Gate on the same number core's `flag_low_confidence` gates on:# `answer_confidence` first, then the entropy `confidence` field, so an@@ -801,16 +810,24 @@ class LayaAgnoGuardrail:hooks_timeout=self.hooks_timeout,)self.last_decision = res- answers = res.get("answers", {})+ # A remote body is arbitrary JSON, so `answers` and each answer are checked before anything+ # is read out of them: `res.get("answers", {})` only defaults when the key is absent, and a+ # present-but-non-object value used to raise AttributeError/TypeError out of the one path+ # whose job is to fail closed. A `noul` value is checked too (`>=` against a string or null+ # is a TypeError, a bool reads as 1.0/0.0, NaN compares False i.e. "safe").+ where = f"Laya server at {self.base_url}" if self.base_url else "Laya"+ answers = _answers_map(res, where)violations: Dict[str, Any] = {}for qid, ans in answers.items():t = ans.get("type")- if t == "noul" and ans.get("noul", 0.0) >= self.threshold:- violations[qid] = {- "probability": ans["noul"],- "confidence": ans.get("confidence", 0.0),- }+ if t == "noul":+ probability = _answer_number(ans, "noul", where)+ if probability >= self.threshold:+ violations[qid] = {+ "probability": probability,+ "confidence": ans.get("confidence", 0.0),+ }elif t == "score":# Gate on the probability that the level is at or above the# middle of the scale – same rule as LayaGuardrail / LayaTaskGuard.diff --git a/laya/integrations/crewai.py b/laya/integrations/crewai.pyindex b5d703e4..a4683cef 100644--- a/laya/integrations/crewai.py+++ b/laya/integrations/crewai.py@@ -57,6 +57,9 @@ class LayaTaskGuardError(ValueError):from ._controls import budget_kwargs as _budget_kwargs, hook_kwargs as _hook_kwargs # noqa: E402from ._controls import decision_kwargs as _decision_kwargs # noqa: E402from ._controls import predict_kwargs as _predict_kwargs, reject_remote_hooks as _reject_remote_hooks # noqa: E402+from ._guard import answer_number as _answer_number # noqa: E402+from ._guard import answers_map as _answers_map # noqa: E402+from ._guard import malformed as _malformed # noqa: E402from ._guard import score_violation_probability as _score_violation_probability # noqa: E402from ..confidence import _gate_confidence # noqa: E402from ._controls import reject_remote_lang_guess as _reject_remote_lang_guess # noqa: E402@@ -363,8 +366,14 @@ class LayaCrewRouter:)self.last_decision = res- ans = res.get("answers", {}).get("delegation", {})+ # The same nested-shape checks as the guardrail screen: `answers` must be an object,+ # the answer must be an object, and `choice` is used with `.startswith` below -- a list+ # there raised AttributeError out of a routing decision.+ where = f"Laya server at {self.base_url}" if self.base_url else "Laya"+ ans = _answers_map(res, where).get("delegation", {})chosen_key = ans.get("choice")+ if chosen_key is not None and not isinstance(chosen_key, str):+ raise _malformed(where, "'choice' must be a string, got %s" % type(chosen_key).__name__)# Gate on the same number core's `flag_low_confidence` gates on: `answer_confidence`# first, falling back to the entropy `confidence` so an answer that carries only the# older field is still gated rather than silently passed (fail-closed). An answer with@@ -542,16 +551,24 @@ class LayaTaskGuard:hooks_timeout=self.hooks_timeout,)self.last_decision = res- answers = res.get("answers", {})+ # A remote body is arbitrary JSON, so `answers` and each answer are checked before anything+ # is read out of them: `res.get("answers", {})` only defaults when the key is absent, and a+ # present-but-non-object value used to raise AttributeError/TypeError out of the one path+ # whose job is to fail closed. A `noul` value is checked too (`>=` against a string or null+ # is a TypeError, a bool reads as 1.0/0.0, NaN compares False i.e. "safe").+ where = f"Laya server at {self.base_url}" if self.base_url else "Laya"+ answers = _answers_map(res, where)violations: Dict[str, Any] = {}for qid, ans in answers.items():t = ans.get("type")- if t == "noul" and ans.get("noul", 0.0) >= self.threshold:- violations[qid] = {- "probability": ans["noul"],- "confidence": ans.get("confidence", 0.0),- }+ if t == "noul":+ probability = _answer_number(ans, "noul", where)+ if probability >= self.threshold:+ violations[qid] = {+ "probability": probability,+ "confidence": ans.get("confidence", 0.0),+ }elif t == "score":# `score` is the expected level (0..k-1), not a probability: gate on the# probability that the level is at or above the middle of the scale.diff --git a/laya/integrations/llamaindex.py b/laya/integrations/llamaindex.pyindex 90a71527..b78c8d8a 100644--- a/laya/integrations/llamaindex.py+++ b/laya/integrations/llamaindex.py@@ -72,6 +72,9 @@ from ._controls import router_kwargs as _router_kwargs # noqa: E402# One class for every integration, so `except LayaLowConfidenceError` catches all of them.from ._errors import LayaLowConfidenceError # noqa: E402+from ._guard import answers_map as _answers_map # noqa: E402+from ._guard import malformed as _malformed # noqa: E402+from ._guard import probability_map as _probability_map # noqa: E402from ..confidence import _gate_confidence # noqa: E402@@ -357,9 +360,16 @@ class LayaSingleSelector(BaseSelector):hooks_timeout=self.hooks_timeout,)self.last_decision = res-- ans = res.get("answers", {}).get("selector", {})+ where = f"Laya server at {self.base_url}" if self.base_url else "Laya"+ # A remote body is arbitrary JSON: `answers`, the answer under `selector` and the fields+ # read out of it are all checked before use, so a malformed body fails closed with a named+ # error instead of raising AttributeError/TypeError out of a routing decision. `choice` is+ # the field that used to crash here -- `.startswith` on a list -- and `confidence` is read+ # through `_gated_confidence`, which already refuses a non-number and a bool.+ ans = _answers_map(res, where).get("selector", {})chosen_key = ans.get("choice")+ if chosen_key is not None and not isinstance(chosen_key, str):+ raise _malformed(where, "'choice' must be a string, got %s" % type(chosen_key).__name__)conf = _gated_confidence(ans)# Map "choice_i" back to index i@@ -508,22 +518,24 @@ class LayaMultiSelector(BaseSelector):hooks_timeout=self.hooks_timeout,)self.last_decision = res+ where = f"Laya server at {self.base_url}" if self.base_url else "Laya"+ # Same checks as the single selector, plus `probabilities`: this one sorts and thresholds+ # every value, so a dict mixing numbers with a string raised TypeError from `sorted`, and a+ # `true` ranked first as 1.0 (bool subclasses int) -- a malformed body could win the+ # selection rather than being refused. Restricting to the caller's own keys also keeps an+ # unknown extra key from winning the ranking.+ ans = _answers_map(res, where).get("selector", {})+ key_list = list(criteria.keys())+ probs = _probability_map(ans, key_list, where)- ans = res.get("answers", {}).get("selector", {})- probs = ans.get("probabilities", {})+ # Sort candidate choices by descending probability. Every key is present in `probs` and each+ # value is a float, so this cannot raise on mixed types any more (it used to).+ ranked = sorted(key_list, key=probs.__getitem__, reverse=True)selected: List[ToolSelection] = []- key_list = list(criteria.keys())-- # Sort candidate choices by descending probability- ranked = sorted(- key_list,- key=lambda k: probs.get(k, 0.0),- reverse=True,- )for key in ranked:- prob = probs.get(key, 0.0)+ prob = probs[key]if prob >= self.probability_threshold:try:idx = int(key.split("_")[1]) if key.startswith("choice_") else key_list.index(key)@@ -667,9 +679,11 @@ class LayaQueryRouter:hooks_timeout=self.hooks_timeout,)self.last_decision = res-- ans = res.get("answers", {}).get("route", {})+ where = f"Laya server at {self.base_url}" if self.base_url else "Laya"+ ans = _answers_map(res, where).get("route", {})chosen = ans.get("choice")+ if chosen is not None and not isinstance(chosen, str):+ raise _malformed(where, "'choice' must be a string, got %s" % type(chosen).__name__)conf = _gated_confidence(ans)if self.confidence_threshold > 0.0 and conf < self.confidence_threshold:diff --git a/tests/test_agno.py b/tests/test_agno.pyindex 6aa1cdaa..92a592b0 100644--- a/tests/test_agno.py+++ b/tests/test_agno.py@@ -799,6 +799,59 @@ check("gate/missing confidence still passes", kept.agent_index, 2)# ---------------------------------------------------------------- Results Summaryprint(f"PASS: {len(PASS)}")++# ------------------------------------------------------ 5c. Malformed NESTED decision fields+#+# The same one-level-deeper shapes as the CrewAI adapter (#1321 guards `answers` itself; these are+# the fields below it). `route` reads `choice` with `.startswith` and `screen` compares `noul` with+# `>=`, so a string/null/bool there raised out of the fail-closed path -- or, for `true`, read as a+# full-probability violation.+_AGNO_NESTED_ROUTE = [+ ({"answers": []}, "answers-list"),+ ({"answers": {"delegation": "agent_1"}}, "answer-str"),+ ({"answers": {"delegation": None}}, "answer-null"),+ ({"answers": {"delegation": {"choice": ["agent_1"]}}}, "choice-list"),+]+for _body, _label in _AGNO_NESTED_ROUTE:+ with patch("urllib.request.build_opener") as _m:+ _m.return_value.open.return_value = DummyHTTPResponse(_body)+ try:+ LayaAgnoRouter(base_url="http://localhost:8000").route(+ "Write a Python function to reverse a string", agents)+ check_true("nested/%s/route raises" % _label, False, "no error raised")+ except RuntimeError as exc:+ check_true("nested/%s/route malformed" % _label,+ "Malformed decision response" in str(exc))+ except Exception as exc:+ check_true("nested/%s/route is RuntimeError" % _label, False, type(exc).__name__)++_AGNO_NESTED_SCREEN = [+ ({"answers": []}, "answers-list"),+ ({"answers": {"harm_severity": "nope"}}, "answer-str"),+ ({"answers": {"harm_severity": {"type": "noul", "noul": "high"}}}, "noul-str"),+ ({"answers": {"harm_severity": {"type": "noul", "noul": None}}}, "noul-null"),+ ({"answers": {"harm_severity": {"type": "noul", "noul": True}}}, "noul-bool"),+]+for _body, _label in _AGNO_NESTED_SCREEN:+ with patch("urllib.request.build_opener") as _m:+ _m.return_value.open.return_value = DummyHTTPResponse(_body)+ try:+ LayaAgnoGuardrail(base_url="http://localhost:8000").screen(+ "Summarize the quarterly report")+ check_true("nested/%s/screen raises" % _label, False, "no error raised")+ except RuntimeError as exc:+ check_true("nested/%s/screen malformed" % _label,+ "Malformed decision response" in str(exc))+ except Exception as exc:+ check_true("nested/%s/screen is RuntimeError" % _label, False, type(exc).__name__)++with patch("urllib.request.build_opener") as _m:+ _m.return_value.open.return_value = DummyHTTPResponse(+ {"answers": {"delegation": {"choice": "agent_0", "answer_confidence": 0.9}}})+ check("nested/well-formed route still routes",+ LayaAgnoRouter(base_url="http://localhost:8000").route(+ "Write a Python function to reverse a string", agents).agent_index, 0)+print(f"FAIL: {len(FAIL)}")for f in FAIL:print(f" - {f}")diff --git a/tests/test_crewai.py b/tests/test_crewai.pyindex ad6a221e..0bbc6a12 100644--- a/tests/test_crewai.py+++ b/tests/test_crewai.py@@ -813,6 +813,68 @@ for _surface, _go in (("router", lambda **kw: LayaCrewRouter(base_url="http://lo# --------------------------------------------------------------- Results Summaryprint(f"PASS: {len(PASS)}")++# ------------------------------------------------------ 4c. Malformed NESTED decision fields+#+# #1301 refuses a top-level non-object and #1321 refuses a non-object `answers`. One level below+# those, both consumers still trusted every nested value: `answers` was iterated with `.items()`,+# each answer was used as a dict, `choice` with `.startswith`, and `noul` compared with `>=`. A+# well-formed object whose `answers` is a list, whose answer is a string, or whose `noul` is a+# string/null/bool raised AttributeError/TypeError out of the fail-closed path -- and a `true` read+# as 1.0 because bool subclasses int, i.e. a spurious full-probability violation.+_CREWAI_NESTED_ROUTE = [+ ({"answers": []}, "answers-list"),+ ({"answers": {"delegation": "agent_1"}}, "answer-str"),+ ({"answers": {"delegation": None}}, "answer-null"),+ ({"answers": {"delegation": {"choice": ["agent_1"]}}}, "choice-list"),+]+for _body, _label in _CREWAI_NESTED_ROUTE:+ with patch("urllib.request.build_opener") as _m:+ _m.return_value.open.return_value = DummyHTTPResponse(_body)+ try:+ LayaCrewRouter(base_url="http://localhost:8000").route(+ "Analyze codebase", agents)+ check_true("nested/%s/route raises" % _label, False, "no error raised")+ except RuntimeError as exc:+ check_true("nested/%s/route malformed" % _label,+ "Malformed decision response" in str(exc))+ except Exception as exc:+ check_true("nested/%s/route is RuntimeError" % _label, False, type(exc).__name__)++_CREWAI_NESTED_SCREEN = [+ ({"answers": []}, "answers-list"),+ ({"answers": {"harm_severity": "nope"}}, "answer-str"),+ ({"answers": {"harm_severity": {"type": "noul", "noul": "high"}}}, "noul-str"),+ ({"answers": {"harm_severity": {"type": "noul", "noul": None}}}, "noul-null"),+ ({"answers": {"harm_severity": {"type": "noul", "noul": True}}}, "noul-bool"),+]+for _body, _label in _CREWAI_NESTED_SCREEN:+ with patch("urllib.request.build_opener") as _m:+ _m.return_value.open.return_value = DummyHTTPResponse(_body)+ try:+ LayaTaskGuard(base_url="http://localhost:8000").screen(+ "Summarize the annual shareholder meeting")+ check_true("nested/%s/screen raises" % _label, False, "no error raised")+ except RuntimeError as exc:+ check_true("nested/%s/screen malformed" % _label,+ "Malformed decision response" in str(exc))+ except Exception as exc:+ check_true("nested/%s/screen is RuntimeError" % _label, False, type(exc).__name__)++# Positive controls: a well-formed body is read exactly as before, on both surfaces.+with patch("urllib.request.build_opener") as _m:+ _m.return_value.open.return_value = DummyHTTPResponse(+ {"answers": {"delegation": {"choice": "agent_2", "answer_confidence": 0.95}}})+ check("nested/well-formed route still routes",+ LayaCrewRouter(base_url="http://localhost:8000").route(+ "Analyze codebase", agents).agent_index, 2)+with patch("urllib.request.build_opener") as _m:+ _m.return_value.open.return_value = DummyHTTPResponse(+ {"answers": {"harm_severity": {"type": "noul", "noul": 0.0, "confidence": 0.9}}})+ check_true("nested/well-formed screen still passes",+ LayaTaskGuard(base_url="http://localhost:8000").screen(+ "Summarize the annual shareholder meeting") is not None)+print(f"FAIL: {len(FAIL)}")for f in FAIL:print(f" - {f}")diff --git a/tests/test_llamaindex.py b/tests/test_llamaindex.pyindex 7615507b..33c94d0f 100644--- a/tests/test_llamaindex.py+++ b/tests/test_llamaindex.py@@ -790,6 +790,66 @@ for _label, _cls, _extra, _run in SURFACES:# --------------------------------------------------------------- Results Summaryprint(f"PASS: {len(PASS)}")++# ------------------------------------------------------ 9c. Malformed NESTED decision fields+#+# One level below the non-object refusal above. The selectors read+# `res.get("answers", {}).get(...)`, use `choice` with `.startswith`, and the multi-selector sorts+# and thresholds `probabilities`, so a string probability raised TypeError from `sorted` and a+# `true` ranked first as 1.0 -- a malformed body could win a selection instead of being refused.+with patch("urllib.request.build_opener") as _m:+ _m.return_value.open.return_value = DummyHTTPResponse({"answers": []})+ for _what, _call in (+ ("single", lambda: LayaSingleSelector(base_url="http://localhost:8000").select(+ tools, "Query via remote server")),+ ("multi", lambda: LayaMultiSelector(base_url="http://localhost:8000",+ probability_threshold=0.3).select(+ tools, "Compare both vector docs")),+ ("router", lambda: LayaQueryRouter(+ query_engines=engines,+ descriptions={"vector": "Semantic search", "sql": "Relational SQL"},+ base_url="http://localhost:8000").route("Run a query")),+ ):+ try:+ _call()+ check_true("nested/answers-list/%s raises" % _what, False, "no error raised")+ except RuntimeError as exc:+ check_true("nested/answers-list/%s malformed" % _what,+ "Malformed decision response" in str(exc))+ except Exception as exc:+ check_true("nested/answers-list/%s is RuntimeError" % _what, False, type(exc).__name__)++_LLAMA_NESTED = [+ ({"answers": {"selector": "choice_0"}}, "single", "answer-str"),+ ({"answers": {"selector": {"choice": ["choice_0"]}}}, "single", "choice-list"),+ ({"answers": {"selector": {"choice": "choice_0", "probabilities": {"choice_0": "90%"}}}},+ "multi", "prob-str"),+ ({"answers": {"selector": {"choice": "choice_0", "probabilities": {"choice_0": True}}}},+ "multi", "prob-bool"),+ ({"answers": {"route": {"choice": [1]}}}, "router", "route-choice-list"),+]+for _body, _surface, _label in _LLAMA_NESTED:+ _surfaces = {+ "single": lambda: LayaSingleSelector(base_url="http://localhost:8000").select(+ tools, "Query via remote server"),+ "multi": lambda: LayaMultiSelector(base_url="http://localhost:8000",+ probability_threshold=0.3).select(+ tools, "Compare both vector docs"),+ "router": lambda: LayaQueryRouter(+ query_engines=engines,+ descriptions={"vector": "Semantic search", "sql": "Relational SQL"},+ base_url="http://localhost:8000").route("Run a query"),+ }+ with patch("urllib.request.build_opener") as _m:+ _m.return_value.open.return_value = DummyHTTPResponse(_body)+ try:+ _surfaces[_surface]()+ check_true("nested/%s raises" % _label, False, "no error raised")+ except RuntimeError as exc:+ check_true("nested/%s malformed" % _label, "Malformed decision response" in str(exc))+ except Exception as exc:+ check_true("nested/%s is RuntimeError" % _label, False, type(exc).__name__)+print(f"FAIL: {len(FAIL)}")for f in FAIL:print(f" - {f}")