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.

test(integrations): a non-object answers field is refused, and a no-decision body is not

Aashish4da6d54184fb
diff --git a/tests/test_agno.py b/tests/test_agno.py
index 6aa1cdaa..232f662b 100644
--- a/tests/test_agno.py
+++ b/tests/test_agno.py
@@ -521,6 +521,72 @@ with patch("urllib.request.build_opener") as _m:
"Write a Python function to reverse a string", agents).agent_index, 2)
+# ---------------------------------------------------------------- 5b. Non-Object `answers` Field
+#
+# Section 5 makes `_call_remote` refuse a top-level array, string, number or `true`/`null`. One level
+# deeper is the same arbitrary JSON: a gateway can answer `{"answers": []}`. `res.get("answers", {})`
+# hands back the list -- the key is present, so the `{}` default never fires -- and both consumers then
+# crash on it: route's delegation lookup with `'list' object has no attribute 'get'`, the guardrail
+# screen with `'list' object has no attribute 'items'`. A crash is not the fail-closed path either.
+# A body without `answers`, or with `answers` as an object (even an empty one), is a no-decision
+# response rather than a malformed one, and has to keep routing and screening exactly as it does today.
+from laya.integrations.agno import _call_remote as _agno_call_remote
+
+_AGNO_BAD_ANSWERS = [
+ (["boom"], "list"),
+ ("boom", "str"),
+ (3, "int"),
+ (True, "bool"),
+ (None, "null"),
+]
+for _answers, _label in _AGNO_BAD_ANSWERS:
+ with patch("urllib.request.build_opener") as _m:
+ _m.return_value.open.return_value = DummyHTTPResponse({"answers": _answers})
+ try:
+ _agno_call_remote("http://localhost:8000", "s", {"q": {}})
+ check_true("badans/%s/_call_remote raises" % _label, False, "no error raised")
+ except RuntimeError as _exc:
+ check_true("badans/%s/names answers" % _label,
+ "'answers' must be a JSON object" in str(_exc), str(_exc))
+ except Exception as _exc:
+ check_true("badans/%s/_call_remote raises" % _label, False, type(_exc).__name__)
+
+ for _entry, _run in (
+ ("route", lambda: LayaAgnoRouter(base_url="http://localhost:8000", api_key="k").route(
+ "Write a Python function to reverse a string", agents)),
+ ("screen", lambda: LayaAgnoGuardrail(base_url="http://localhost:8000",
+ api_key="k").screen(safe_msg)),
+ ):
+ try:
+ _run()
+ check_true("badans/%s/%s raises" % (_label, _entry), False, "no error raised")
+ except RuntimeError:
+ check_true("badans/%s/%s raises" % (_label, _entry), True)
+ except Exception as _exc:
+ check_true("badans/%s/%s raises" % (_label, _entry), False, type(_exc).__name__)
+
+# The refusal names the offending type -- with `answers` nested inside an otherwise valid body, that
+# is the only thing a caller reading a log line can act on.
+with patch("urllib.request.build_opener") as _m:
+ _m.return_value.open.return_value = DummyHTTPResponse({"answers": ["boom"]})
+ try:
+ _agno_call_remote("http://localhost:8000", "s", {"q": {}})
+ check_true("badans/names the type", False, "no error raised")
+ except RuntimeError as _exc:
+ check_true("badans/names the type", "got list" in str(_exc), str(_exc))
+
+# Controls: the two no-decision shapes still route and still screen.
+for _body, _label in (({"model": "laya-multilingual"}, "answers absent"),
+ ({"answers": {}}, "answers empty")):
+ with patch("urllib.request.build_opener") as _m:
+ _m.return_value.open.return_value = DummyHTTPResponse(_body)
+ check("badans/%s still routes" % _label,
+ LayaAgnoRouter(base_url="http://localhost:8000").route(
+ "Write a Python function to reverse a string", agents).agent_index, 0)
+ check("badans/%s still screens safe" % _label,
+ LayaAgnoGuardrail(base_url="http://localhost:8000").screen(safe_msg), safe_msg)
+
+
# ---------------------------------------------------------------- 6. Per-call decision controls
#
# The agno module must accept every control in `._controls` – a control added
diff --git a/tests/test_crewai.py b/tests/test_crewai.py
index ad6a221e..b2f55388 100644
--- a/tests/test_crewai.py
+++ b/tests/test_crewai.py
@@ -426,6 +426,73 @@ with patch("urllib.request.build_opener") as _m:
"Analyze codebase", agents).agent_index, 1)
+# --------------------------------------------------------------- 4c. Non-Object `answers` Field
+#
+# Section 4b makes `_call_remote` refuse a top-level array, string, number or `true`/`null`. One level
+# deeper is the same arbitrary JSON: a gateway can answer `{"answers": []}`. `res.get("answers", {})`
+# hands back the list -- the key is present, so the `{}` default never fires -- and both consumers then
+# crash on it: route's delegation lookup with `'list' object has no attribute 'get'`, the guardrail
+# screen with `'list' object has no attribute 'items'`. A crash is not the fail-closed path either.
+# A body without `answers`, or with `answers` as an object (even an empty one), is a no-decision
+# response rather than a malformed one, and has to keep routing and screening exactly as it does today.
+from laya.integrations.crewai import _call_remote as _crewai_call_remote
+
+_CREWAI_BAD_ANSWERS = [
+ (["boom"], "list"),
+ ("boom", "str"),
+ (3, "int"),
+ (True, "bool"),
+ (None, "null"),
+]
+for _answers, _label in _CREWAI_BAD_ANSWERS:
+ with patch("urllib.request.build_opener") as _m:
+ _m.return_value.open.return_value = DummyHTTPResponse({"answers": _answers})
+ try:
+ _crewai_call_remote("http://localhost:8000", "s", {"q": {}})
+ check_true("badans/%s/_call_remote raises" % _label, False, "no error raised")
+ except RuntimeError as _exc:
+ check_true("badans/%s/names answers" % _label,
+ "'answers' must be a JSON object" in str(_exc), str(_exc))
+ except Exception as _exc:
+ check_true("badans/%s/_call_remote raises" % _label, False, type(_exc).__name__)
+
+ for _entry, _run in (
+ ("route", lambda a=_answers: LayaCrewRouter(base_url="http://localhost:8000",
+ api_key="k").route(
+ "Analyze codebase", agents)),
+ ("screen", lambda a=_answers: LayaTaskGuard(base_url="http://localhost:8000",
+ api_key="k").screen("hello")),
+ ):
+ try:
+ _run()
+ check_true("badans/%s/%s raises" % (_label, _entry), False, "no error raised")
+ except RuntimeError:
+ check_true("badans/%s/%s raises" % (_label, _entry), True)
+ except Exception as _exc:
+ check_true("badans/%s/%s raises" % (_label, _entry), False, type(_exc).__name__)
+
+# The refusal names the offending type -- with `answers` nested inside an otherwise valid body, that
+# is the only thing a caller reading a log line can act on.
+with patch("urllib.request.build_opener") as _m:
+ _m.return_value.open.return_value = DummyHTTPResponse({"answers": ["boom"]})
+ try:
+ _crewai_call_remote("http://localhost:8000", "s", {"q": {}})
+ check_true("badans/names the type", False, "no error raised")
+ except RuntimeError as _exc:
+ check_true("badans/names the type", "got list" in str(_exc), str(_exc))
+
+# Controls: the two no-decision shapes still route and still screen.
+for _body, _label in (({"model": "laya-multilingual"}, "answers absent"),
+ ({"answers": {}}, "answers empty")):
+ with patch("urllib.request.build_opener") as _m:
+ _m.return_value.open.return_value = DummyHTTPResponse(_body)
+ check("badans/%s still routes" % _label,
+ LayaCrewRouter(base_url="http://localhost:8000").route(
+ "Analyze codebase", agents).agent_index, 0)
+ check("badans/%s still screens safe" % _label,
+ LayaTaskGuard(base_url="http://localhost:8000").screen("hello"), "hello")
+
+
# --------------------------------------------------------------- 5. Per-call decision controls
#
# `laya.integrations.langchain` has forwarded `max_len` / `head_max_len` and the five hook
diff --git a/tests/test_langchain.py b/tests/test_langchain.py
index 5c187d01..32a74d52 100644
--- a/tests/test_langchain.py
+++ b/tests/test_langchain.py
@@ -1839,6 +1839,98 @@ finally:
langchain_module.urllib.request.build_opener = _orig_build_opener_lc
+# --------------------------------------------------------------- Non-Object `answers` Field
+#
+# The section above makes `_call_remote` refuse a top-level array, string, number or `true`/`null`.
+# One level deeper is the same arbitrary JSON: a gateway can answer `{"answers": []}`. Reading
+# `result.get("answers", {})` hands back the list -- the key is present, so the `{}` default never
+# fires -- and the four consumers then either crash (`LayaRouter` subscripts it, the guardrail calls
+# `.items()` on it, the triage `.get("intent", …)`) or hand a non-mapping straight back to user code.
+# None of those is a documented outcome. `answers` absent and `answers` an empty object are the
+# no-decision cases that already have their own behaviour, and that behaviour is pinned unchanged here.
+_LC_BAD_ANSWERS = [
+ (["boom"], "list"),
+ ("boom", "str"),
+ (3, "int"),
+ (True, "bool"),
+ (None, "null"),
+]
+_LC_CRITERIA = {"billing": "invoices, refunds", "technical": "bugs, errors"}
+_lc_orig_opener_badans = langchain_module.urllib.request.build_opener
+try:
+ for _answers, _label in _LC_BAD_ANSWERS:
+ _raw_bad = json.dumps({"answers": _answers})
+ langchain_module.urllib.request.build_opener = (
+ lambda *a, _r=_raw_bad: _RawBodyOpener(_r))
+ try:
+ langchain_module._call_remote("http://localhost:8000", "s", {"q": {}})
+ check_true("badans/%s/_call_remote raises" % _label, False, "no error raised")
+ except RuntimeError as _e:
+ check_true("badans/%s/names answers" % _label,
+ "'answers' must be a JSON object" in str(_e), str(_e))
+ except Exception as _e:
+ check_true("badans/%s/_call_remote raises" % _label, False, type(_e).__name__)
+
+ for _entry, _run in (
+ ("router", lambda: LayaRouter(criteria=_LC_CRITERIA, base_url="http://localhost:8000",
+ api_key="k").invoke("I need an invoice refund")),
+ ("guardrail", lambda: LayaGuardrail(base_url="http://localhost:8000",
+ api_key="k").invoke(
+ "What is the capital of France?")),
+ ("triage", lambda: LayaTriage(base_url="http://localhost:8000",
+ api_key="k").invoke({"state": "I want a refund"})),
+ ):
+ try:
+ _run()
+ check_true("badans/%s/%s raises" % (_label, _entry), False, "no error raised")
+ except RuntimeError:
+ check_true("badans/%s/%s raises" % (_label, _entry), True)
+ except Exception as _e:
+ check_true("badans/%s/%s raises" % (_label, _entry), False, type(_e).__name__)
+
+ # The refusal names the offending type -- with `answers` nested inside an otherwise valid body,
+ # that is the only thing a caller reading a log line can act on.
+ langchain_module.urllib.request.build_opener = (
+ lambda *a: _RawBodyOpener(json.dumps({"answers": ["boom"]})))
+ try:
+ langchain_module._call_remote("http://localhost:8000", "s", {"q": {}})
+ check_true("badans/names the type", False, "no error raised")
+ except RuntimeError as _e:
+ check_true("badans/names the type", "got list" in str(_e), str(_e))
+
+ # Controls: a real decision still routes, screens and triages...
+ langchain_module.urllib.request.build_opener = (lambda *a: _RawBodyOpener(json.dumps({
+ "answers": {
+ "route": {"type": "choice", "choice": "billing",
+ "confidence": 0.9, "answer_confidence": 0.9},
+ }})))
+ check("badans/object still routes",
+ LayaRouter(criteria=_LC_CRITERIA, base_url="http://localhost:8000").invoke(
+ "I need an invoice refund"), "billing")
+ check("badans/object still screens safe",
+ LayaGuardrail(base_url="http://localhost:8000").invoke(
+ "What is the capital of France?"), "What is the capital of France?")
+ check_true("badans/object still triages",
+ isinstance(LayaTriage(base_url="http://localhost:8000").invoke(
+ {"state": "I want a refund"}), dict))
+
+ # ...and an empty-but-object `answers` keeps the two no-decision behaviours it already had: the
+ # router's own KeyError naming the question it asked, the guardrail reporting no violations.
+ langchain_module.urllib.request.build_opener = (
+ lambda *a: _RawBodyOpener(json.dumps({"answers": {}})))
+ check("badans/empty answers still screens safe",
+ LayaGuardrail(base_url="http://localhost:8000").invoke(
+ "What is the capital of France?"), "What is the capital of France?")
+ try:
+ LayaRouter(criteria=_LC_CRITERIA, base_url="http://localhost:8000").invoke(
+ "I need an invoice refund")
+ check_true("badans/empty answers keeps its KeyError", False, "no error raised")
+ except KeyError as _e:
+ check_true("badans/empty answers keeps its KeyError", str(_e) == "'route'", str(_e))
+finally:
+ langchain_module.urllib.request.build_opener = _lc_orig_opener_badans
+
+
# --------------------------------------------------------------- Summary
print(f"PASS: {len(PASS)}")
print(f"FAIL: {len(FAIL)}")
diff --git a/tests/test_llamaindex.py b/tests/test_llamaindex.py
index 7615507b..b281e21d 100644
--- a/tests/test_llamaindex.py
+++ b/tests/test_llamaindex.py
@@ -442,6 +442,75 @@ with patch("urllib.request.build_opener") as _m:
tools, "Query via remote server").selections[0].index, 1)
+# --------------------------------------------------------------- 5b. Non-Object `answers` Field
+#
+# Section 5 makes `_call_remote` refuse a top-level array, string, number or `true`/`null`. One level
+# deeper is the same arbitrary JSON: a gateway can answer `{"answers": []}`. `res.get("answers", {})`
+# hands back the list -- the key is present, so the `{}` default never fires -- and the lookup then
+# crashes on `'list' object has no attribute 'get'`, which is not the fail-closed path. Three call
+# sites read it that way (the single selector, the multi selector and the query router); the two with
+# different answer keys are driven here, and the multi selector shares the single one's line. A body
+# without `answers`, or with `answers` as an object (even an empty one), is a no-decision response
+# rather than a malformed one, and has to keep selecting and routing exactly as it does today.
+from laya.integrations.llamaindex import _call_remote as _llama_call_remote
+
+_LLAMA_BAD_ANSWERS = [
+ (["boom"], "list"),
+ ("boom", "str"),
+ (3, "int"),
+ (True, "bool"),
+ (None, "null"),
+]
+for _answers, _label in _LLAMA_BAD_ANSWERS:
+ with patch("urllib.request.build_opener") as _m:
+ _m.return_value.open.return_value = DummyHTTPResponse({"answers": _answers})
+ try:
+ _llama_call_remote("http://localhost:8000", "s", {"q": {}})
+ check_true("badans/%s/_call_remote raises" % _label, False, "no error raised")
+ except RuntimeError as _exc:
+ check_true("badans/%s/names answers" % _label,
+ "'answers' must be a JSON object" in str(_exc), str(_exc))
+ except Exception as _exc:
+ check_true("badans/%s/_call_remote raises" % _label, False, type(_exc).__name__)
+
+ for _entry, _run in (
+ ("select", lambda: LayaSingleSelector(base_url="http://localhost:8000",
+ api_key="k").select(
+ tools, "Query via remote server")),
+ ("route", lambda: LayaQueryRouter(query_engines=engines, base_url="http://localhost:8000",
+ api_key="k").route("Query via remote server")),
+ ):
+ try:
+ _run()
+ check_true("badans/%s/%s raises" % (_label, _entry), False, "no error raised")
+ except RuntimeError:
+ check_true("badans/%s/%s raises" % (_label, _entry), True)
+ except Exception as _exc:
+ check_true("badans/%s/%s raises" % (_label, _entry), False, type(_exc).__name__)
+
+# The refusal names the offending type -- with `answers` nested inside an otherwise valid body, that
+# is the only thing a caller reading a log line can act on.
+with patch("urllib.request.build_opener") as _m:
+ _m.return_value.open.return_value = DummyHTTPResponse({"answers": ["boom"]})
+ try:
+ _llama_call_remote("http://localhost:8000", "s", {"q": {}})
+ check_true("badans/names the type", False, "no error raised")
+ except RuntimeError as _exc:
+ check_true("badans/names the type", "got list" in str(_exc), str(_exc))
+
+# Controls: the two no-decision shapes still select and still route.
+for _body, _label in (({"model": "laya-multilingual"}, "answers absent"),
+ ({"answers": {}}, "answers empty")):
+ with patch("urllib.request.build_opener") as _m:
+ _m.return_value.open.return_value = DummyHTTPResponse(_body)
+ check("badans/%s still selects" % _label,
+ LayaSingleSelector(base_url="http://localhost:8000").select(
+ tools, "Query via remote server").selections[0].index, 0)
+ check("badans/%s still routes" % _label,
+ LayaQueryRouter(query_engines=engines, base_url="http://localhost:8000").route(
+ "Query via remote server"), next(iter(engines)))
+
+
# --------------------------------------------------------------- 6. Per-call decision controls
#
# `laya.integrations.langchain` has forwarded `max_len` / `head_max_len` and the five hook