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(agent): preserve start-hook questions in long scans
kapelamee9bafe57b4a9
diff --git a/laya/agent.py b/laya/agent.pyindex 5ca3861c..a36d18ba 100644--- a/laya/agent.py+++ b/laya/agent.py@@ -239,11 +239,18 @@ def _start_evidence():inference, `states` is a snapshot of the states that reached it (`None` if the probe never ran,which means `predict_batch` was replaced and no hook chain was dispatched)."""- evidence = {"answered": False, "states": None}+ evidence = {"answered": False, "states": None, "question_types": None}def probe(ctx):evidence["answered"] = ctx.results is not Noneevidence["states"] = list(ctx.states)+ # Snapshot only the inference schema; leave malformed questions to predict_batch's+ # validator, and do not inspect questions when a hook has already answered the call.+ if ctx.results is None and isinstance(ctx.questions, dict):+ evidence["question_types"] = {+ qid: qdef.get("type") if isinstance(qdef, dict) else None+ for qid, qdef in ctx.questions.items()+ }return probe, evidence@@ -1246,12 +1253,13 @@ class Agent(HookRegistry):return {"model": "laya-rl-agent", "answers": {},"usage": {**aggregate_usage(results), "windows": 0}}- ids = list(questions.keys())- internal = {qid: self._to_internal(questions[qid]) for qid in ids}+ question_types = evidence["question_types"]+ if question_types is None: # a replacement predict_batch may not dispatch hooks+ question_types = {qid: self._to_internal(qdef)["t"] for qid, qdef in questions.items()}answers = {}- for qid in ids:+ for qid, qtype in question_types.items():per = [r["answers"][qid] for r in results]- if internal[qid]["t"] == "noul":+ if qtype == "noul":# Evidence anywhere: the strongest window decides. Its own P(true) and confidence# (and act) are carried through, so the fields stay mutually consistent.best = max(range(len(per)), key=lambda j: float(per[j]["noul"]))diff --git a/laya/onnx_agent.py b/laya/onnx_agent.pyindex c31778a9..55776443 100644--- a/laya/onnx_agent.py+++ b/laya/onnx_agent.py@@ -487,12 +487,13 @@ class ONNXAgent(HookRegistry):return {"model": "laya-rl-agent-onnx", "answers": {},"usage": {**aggregate_usage(results), "windows": 0}}- ids = list(questions.keys())- internal = {qid: self._to_internal(questions[qid]) for qid in ids}+ question_types = evidence["question_types"]+ if question_types is None: # a replacement predict_batch may not dispatch hooks+ question_types = {qid: self._to_internal(qdef)["t"] for qid, qdef in questions.items()}answers = {}- for qid in ids:+ for qid, qtype in question_types.items():per = [r["answers"][qid] for r in results]- if internal[qid]["t"] == "noul":+ if qtype == "noul":# Evidence anywhere: the strongest window decides, carrying its own P(true),# confidence and act so the fields stay mutually consistent.best = max(range(len(per)), key=lambda j: float(per[j]["noul"]))diff --git a/tests/test_onnx_long.py b/tests/test_onnx_long.pyindex 035dbc7f..b021ac6f 100644--- a/tests/test_onnx_long.py+++ b/tests/test_onnx_long.py@@ -207,6 +207,55 @@ check("empty/no questions -> empty answers, windowed usage",({}, True, True))+# ---------------------------------------------------------------- start hooks may replace questions+question_rewrites = [+ ("append", {**QUESTIONS, "review": QUESTIONS["urgent"]}),+ ("replace", {"review": QUESTIONS["urgent"]}),+ ("delete", {"urgent": QUESTIONS["urgent"]}),+ ("clear", {}),+ ("choice to noul", {**QUESTIONS, "dept": QUESTIONS["urgent"]}),+ ("noul to choice", {**QUESTIONS, "urgent": QUESTIONS["dept"]}),+]+for name, rewritten_questions in question_rewrites:+ expected = _bare_onnx().predict_long(LONG_STATE, rewritten_questions)+ try:+ actual = _bare_onnx().predict_long(+ LONG_STATE, QUESTIONS,+ on_predict_start=lambda ctx: setattr(ctx, "questions", rewritten_questions))+ except Exception as exc:+ FAIL.append("questions/%s raised %r" % (name, exc))+ else:+ check("questions/%s matches directly requesting the final schema" % name, actual, expected)++check("questions/no-op preserves the unhooked result",+ _bare_onnx().predict_long(LONG_STATE, QUESTIONS, on_predict_start=lambda ctx: None),+ _bare_onnx().predict_long(LONG_STATE, QUESTIONS))+++def _annotate_first_window(ctx):+ ctx.results[0]["answers"]["review"] = {"type": "noul", "noul": 0.9, "answer_confidence": 0.9}+++expected = _bare_onnx().predict_long(LONG_STATE, QUESTIONS)+try:+ actual = _bare_onnx().predict_long(LONG_STATE, QUESTIONS, on_predict_end=_annotate_first_window)+except Exception as exc:+ FAIL.append("questions/a first-window end annotation raised %r" % exc)+else:+ check("questions/a first-window end annotation preserves the scan's answers", actual, expected)++for malformed in (None, [], {"bad": None}, {"bad": {}}, {"bad": {"type": "unknown"}}):+ errors = []+ for method in ("system_one", "predict_long"):+ try:+ getattr(_bare_onnx(), method)(LONG_STATE, malformed)+ except Exception as exc:+ errors.append((type(exc).__name__, str(exc)))+ else:+ errors.append(None)+ check("questions/invalid input keeps the validator's error: %r" % malformed, errors[1], errors[0])++# ---------------------------------------------------------------- reportprint("\n%d passed, %d failed" % (len(PASS), len(FAIL)))for f in FAIL:diff --git a/tests/test_predict_long.py b/tests/test_predict_long.pyindex 67d54d69..02d29f07 100644--- a/tests/test_predict_long.py+++ b/tests/test_predict_long.py@@ -426,6 +426,59 @@ check("rewrite/the same length is still the same count",check("rewrite/a text rewrite names no span",sorted(k for v in (upper or {}).get("answers", {}).values() for k in v if k == "window"), [])+# A shared start hook may add a review question or replace the request's schema. Aggregate the+# questions that actually ran, just as a short state does, including a changed type under one id.+def _question_agent():+ a = make_real_agent()+ a.temperature, a.temperature_by_options, a.lang_temperatures = [1.0] * 3, {}, {}+ del a._decode_answers # exercise the real typed answer decoder++ def forward(b):+ n = b["input_ids"].shape[0]+ logits = np.tile(np.array([[0.0, 1.4]], dtype=np.float32), (n, 1))+ logits[0] = [3.0, 0.0] # most confident differs from strongest P(true)+ return logits, np.full((n, 2), 0.5, dtype=np.float32)++ a._forward = forward+ return a+++question_rewrites = [+ ("append", {**Q, "review": Q["flag"]}),+ ("replace", {"review": Q["flag"]}),+ ("delete", {"flag": Q["flag"]}),+ ("clear", {}),+ ("choice to noul", {**Q, "dept": Q["flag"]}),+ ("noul to choice", {**Q, "flag": Q["dept"]}),+]+for name, rewritten_questions in question_rewrites:+ expected = _question_agent().predict_long(LONG, rewritten_questions)+ actual, exc = _attempt(lambda: _question_agent().predict_long(+ LONG, Q, on_predict_start=lambda ctx: setattr(ctx, "questions", rewritten_questions)))+ check("questions/%s returns without error" % name, _kind(exc), None)+ check("questions/%s matches directly requesting the final schema" % name, actual, expected)++check("questions/no-op preserves the unhooked result",+ _question_agent().predict_long(LONG, Q, on_predict_start=lambda ctx: None),+ _question_agent().predict_long(LONG, Q))++# An end hook may annotate only one window. Extra answers are not questions in the scan.+def _annotate_first_window(ctx):+ ctx.results[0]["answers"]["review"] = {"type": "noul", "noul": 0.9, "answer_confidence": 0.9}+++expected = _question_agent().predict_long(LONG, Q)+actual, exc = _attempt(lambda: _question_agent().predict_long(LONG, Q, on_predict_end=_annotate_first_window))+check("questions/a first-window end annotation preserves the scan's answers", actual, expected)+check("questions/a first-window end annotation does not require other windows to match", _kind(exc), None)++# The recorder must leave invalid input to predict_batch's existing question validation.+for malformed in (None, [], {"bad": None}, {"bad": {}}, {"bad": {"type": "unknown"}}):+ _, direct_exc = _attempt(lambda: _question_agent().system_one(LONG, malformed))+ _, long_exc = _attempt(lambda: _question_agent().predict_long(LONG, malformed))+ check("questions/invalid input keeps the validator's error: %r" % malformed,+ (_kind(long_exc), str(long_exc)), (_kind(direct_exc), str(direct_exc)))+# 8e. a hook that leaves nothing scores nothing: 0 windows and no answers, not a max() over []a = make_real_agent()with warnings.catch_warnings(record=True) as caught: